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

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

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

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 ClinicRequestGrid_ListPatientRequestsForClinic2(
  $clinicSlug: String!,
  $queueId: String,
  $queueAssignment: QueueAssignmentFilter!,
  $pageInfo: PageInfo!,
  $locale: Locale!,
  $state: PatientRequestState
) {
  requestsResponse: listPatientRequestsForClinic2(
    clinicSlug: $clinicSlug,
    queueId: $queueId,
    queueAssignment: $queueAssignment,
    pageInfo: $pageInfo,
    state: $state
  ) {
    count
    patientRequests {
      id
      displayTitle(locale: $locale)
      createdAt
      updatedAt
      doneAt
      removedAt
      extendedPatient {
        name
        surname
        identificationNumber
      }
    }
  }
}
"""

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

# ================================
# 📡 FETCH FUNCTION
# ================================
def fetch_requests(headers, state, offset=0):
    """Fetch a batch of patient requests for a given state."""
    variables = {
        "clinicSlug": CLINIC_SLUG,
        "queueId": None,
        "queueAssignment": "ANY",
        "pageInfo": {"first": BATCH_SIZE, "offset": offset},
        "locale": "cs",
        "state": state,
    }
    payload = {
        "operationName": "ClinicRequestGrid_ListPatientRequestsForClinic2",
        "query": GRAPHQL_QUERY,
        "variables": variables,
    }

    for attempt in range(3):  # up to 3 attempts
        try:
            r = requests.post("https://api.medevio.cz/graphql", json=payload, headers=headers, timeout=30)
            r.raise_for_status()
            resp = r.json().get("data", {}).get("requestsResponse", {})
            return resp.get("patientRequests", []), resp.get("count", 0)
        except requests.exceptions.RequestException as e:
            print(f"⚠️  Chyba při načítání (pokus {attempt+1}/3): {e}")
            time.sleep(5)
    return [], 0

# ================================
# 💾 UPDATE ALL MESSAGES BY PATIENT DATA
# ================================
def update_all_messages(conn, patient):
    """Update all messages belonging to this request with patient data."""
    p = patient.get("extendedPatient") or {}
    if not p:
        return 0

    sql = """
        UPDATE medevio_messages
        SET pacient_jmeno=%s,
            pacient_prijmeni=%s,
            pacient_rodnecislo=%s
        WHERE request_id=%s
    """
    vals = (p.get("name"), p.get("surname"), p.get("identificationNumber"), patient.get("id"))
    with conn.cursor() as cur:
        cur.execute(sql, vals)
        affected = cur.rowcount
    conn.commit()
    return affected

# ================================
# 🧠 MAIN
# ================================
def process_state(conn, headers, state):
    print(f"\n=== 🟦 Zpracovávám {state} požadavky ===")
    offset = 0
    total_processed = 0
    total_updated = 0

    while True:
        batch, total_count = fetch_requests(headers, state, offset)
        if not batch:
            break

        print(f"📦 Dávka od offsetu {offset} ({len(batch)} záznamů z {total_count})")
        for r in batch:
            updated = update_all_messages(conn, r)
            total_processed += 1
            total_updated += updated
            if updated:
                print(f"   ↳ {r.get('id')} → {updated} zpráv aktualizováno")

        offset += BATCH_SIZE
        if offset >= total_count:
            break

        time.sleep(0.4)

    print(f"✅ {state}: zpracováno {total_processed} požadavků, aktualizováno {total_updated} zpráv.")
    return total_processed, total_updated

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

    conn = pymysql.connect(**DB_CONFIG)

    print(f"\n=== Medevio mass patient sync @ {datetime.now():%Y-%m-%d %H:%M:%S} ===")

    total_p, total_u = process_state(conn, headers, "ACTIVE")
    done_p, done_u = process_state(conn, headers, "DONE")

    conn.close()

    print("\n=== 🧾 SOUHRN ===")
    print(f"ACTIVE: {total_p} požadavků, {total_u} zpráv aktualizováno")
    print(f"DONE:   {done_p} požadavků, {done_u} zpráv aktualizováno")
    print("===========================================")
    print(f"CELKEM: {total_p + done_p} požadavků, {total_u + done_u} zpráv aktualizováno ✅")

if __name__ == "__main__":
    main()
