#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pymysql
import requests
from datetime import datetime
from pathlib import Path
import time, socket

# ===============================
# ⚙️ CONFIG
# ===============================
TOKEN_PATH = Path(__file__).resolve().parent.parent / "token.txt"
CLINIC_SLUG = "mudr-buzalkova"

DB_CONFIG = {
    "host": "192.168.1.76",
    "port": 3307,
    "user": "root",
    "password": "Vlado9674+",
    "database": "medevio",
    "charset": "utf8mb4",
    "cursorclass": pymysql.cursors.DictCursor,
}

GRAPHQL_QUERY = r"""
query ClinicRequestDetail_GetMessages(
  $clinicSlug: String!,
  $requestId: ID!
) {
  clinicRequestDetail_GetPatientRequestMessages(
    clinicSlug: $clinicSlug,
    requestId: $requestId
  ) {
    id
    text
    createdAt
    sender {
      id
      name
    }
    extendedPatient {
      name
      surname
      identificationNumber
    }
  }
}
"""

# ===============================
# 🔑 Token reader
# ===============================
def read_token(path: Path) -> str:
    tok = path.read_text(encoding="utf-8").strip()
    return tok.split(" ", 1)[1] if tok.startswith("Bearer ") else tok

# ===============================
# 🕒 Helper
# ===============================
def to_mysql_dt(iso_str):
    if not iso_str:
        return None
    try:
        dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
        return dt.strftime("%Y-%m-%d %H:%M:%S")
    except Exception:
        return None

# ===============================
# 💾 Upsert
# ===============================
def upsert_message(conn, msg, request_id):
    s = msg.get("sender") or {}
    p = msg.get("extendedPatient") or {}

    sql = """
    INSERT INTO medevio_messages (
        id, request_id, sender_name, sender_id, text, created_at,
        pacient_jmeno, pacient_prijmeni, pacient_rodnecislo
    ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
    ON DUPLICATE KEY UPDATE
        text=VALUES(text),
        created_at=VALUES(created_at),
        pacient_jmeno=VALUES(pacient_jmeno),
        pacient_prijmeni=VALUES(pacient_prijmeni),
        pacient_rodnecislo=VALUES(pacient_rodnecislo)
    """

    vals = (
        msg.get("id"),
        request_id,
        s.get("name"),
        s.get("id"),
        msg.get("text"),
        to_mysql_dt(msg.get("createdAt")),
        p.get("name"),
        p.get("surname"),
        p.get("identificationNumber"),
    )

    with conn.cursor() as cur:
        cur.execute(sql, vals)
    conn.commit()

# ===============================
# 📡 Fetch messages for one request
# ===============================
def fetch_messages(headers, request_id):
    payload = {
        "operationName": "ClinicRequestDetail_GetMessages",
        "query": GRAPHQL_QUERY,
        "variables": {"clinicSlug": CLINIC_SLUG, "requestId": request_id},
    }
    r = requests.post("https://api.medevio.cz/graphql", json=payload, headers=headers)
    r.raise_for_status()
    data = r.json().get("data", {}).get("clinicRequestDetail_GetPatientRequestMessages", [])
    return data

# ===============================
# 🧠 Main
# ===============================
def main():
    token = read_token(TOKEN_PATH)
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }

    conn = pymysql.connect(**DB_CONFIG)
    cur = conn.cursor()

    # vezmeme všechny request_id z tabulky pozadavky
    cur.execute("SELECT id FROM pozadavky ORDER BY updatedAt DESC")
    request_ids = [r["id"] for r in cur.fetchall()]
    print(f"📋 Found {len(request_ids)} požadavků.")

    for i, rid in enumerate(request_ids, 1):
        try:
            msgs = fetch_messages(headers, rid)
            for msg in msgs:
                upsert_message(conn, msg, rid)
            print(f"[{i}/{len(request_ids)}] {rid} → {len(msgs)} zpráv uloženo.")
            time.sleep(0.4)
        except Exception as e:
            print(f"❌ Chyba při načítání {rid}: {e}")

    conn.close()
    print("\n✅ Hotovo, všechny zprávy synchronizovány.")

if __name__ == "__main__":
    main()
