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

"""
Download and store Medevio questionnaires (userNote + eCRF) for all patient requests.
Uses the verified working query "GetPatientRequest2".
"""

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

# Force UTF-8 output even under Windows Task Scheduler
try:
    sys.stdout.reconfigure(encoding='utf-8')
    sys.stderr.reconfigure(encoding='utf-8')
except AttributeError:
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')


# ==============================
# 🛡 SAFE PRINT FOR CP1250 / EMOJI
# ==============================
def safe_print(text: str):
    enc = sys.stdout.encoding or ""
    if not enc.lower().startswith("utf"):
        text = ''.join(ch for ch in text if ord(ch) < 65536)
    try:
        print(text)
    except UnicodeEncodeError:
        text = ''.join(ch for ch in text if ord(ch) < 128)
        print(text)


# ==============================
# 🔧 CONFIGURATION (UPDATED TO 192.168.1.50)
# ==============================
TOKEN_PATH = Path(__file__).resolve().parent.parent / "token.txt"
CLINIC_SLUG = "mudr-buzalkova"
GRAPHQL_URL = "https://api.medevio.cz/graphql"

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


# ==============================
# 🕒 DATETIME FIXER
# ==============================
def fix_datetime(dt_str):
    if not dt_str:
        return None
    try:
        return datetime.fromisoformat(dt_str.replace("Z", "").replace("+00:00", ""))
    except Exception:
        return None


# Optional filter
CREATED_AFTER = "2025-01-01"


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


GRAPHQL_QUERY = r"""
query GetPatientRequest2($requestId: UUID!, $clinicSlug: String!, $locale: Locale!) {
  request: getPatientRequest2(patientRequestId: $requestId, clinicSlug: $clinicSlug) {
    id
    displayTitle(locale: $locale)
    createdAt
    updatedAt
    userNote
    eventType
    extendedPatient(clinicSlug: $clinicSlug) {
      name
      surname
      identificationNumber
    }
    ecrfFilledData(locale: $locale) {
      name
      groups {
        label
        fields {
          name
          label
          type
          value
        }
      }
    }
  }
}
"""


def fetch_questionnaire(headers, request_id, clinic_slug):
    payload = {
        "operationName": "GetPatientRequest2",
        "query": GRAPHQL_QUERY,
        "variables": {
            "requestId": request_id,
            "clinicSlug": clinic_slug,
            "locale": "cs",
        },
    }
    r = requests.post(GRAPHQL_URL, json=payload, headers=headers, timeout=40)
    if r.status_code != 200:
        safe_print(f"❌ HTTP {r.status_code} for {request_id}: {r.text}")
        return None
    return r.json().get("data", {}).get("request")


def insert_questionnaire(cur, req):
    if not req:
        return

    patient = req.get("extendedPatient") or {}
    ecrf_data = req.get("ecrfFilledData")
    created_at = fix_datetime(req.get("createdAt"))
    updated_at = fix_datetime(req.get("updatedAt"))

    cur.execute("""
        INSERT INTO medevio_questionnaires (
            request_id, created_at, updated_at, user_note, ecrf_json
        )
        VALUES (%s,%s,%s,%s,%s)
        ON DUPLICATE KEY UPDATE
            updated_at = VALUES(updated_at),
            user_note = VALUES(user_note),
            ecrf_json = VALUES(ecrf_json),
            updated_local = NOW()
    """, (
        req.get("id"),
        created_at,
        updated_at,
        req.get("userNote"),
        json.dumps(ecrf_data, ensure_ascii=False),
    ))

    safe_print(f"   💾 Stored questionnaire for {patient.get('surname','')} {patient.get('name','')}")


# ==============================
# 🧠 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)

    # load list of requests from the table we just filled
    with conn.cursor() as cur:
        sql = """
            SELECT id, pacient_jmeno, pacient_prijmeni, createdAt, updatedAt, questionnaireprocessed
            FROM pozadavky
            WHERE (questionnaireprocessed IS NULL OR questionnaireprocessed < updatedAt)
        """
        if CREATED_AFTER:
            sql += " AND createdAt >= %s"
            cur.execute(sql, (CREATED_AFTER,))
        else:
            cur.execute(sql)

        rows = cur.fetchall()

    safe_print(f"📋 Found {len(rows)} requests needing questionnaire check.")

    for i, row in enumerate(rows, 1):
        req_id = row["id"]
        safe_print(f"\n[{i}/{len(rows)}] 🔍 Fetching questionnaire for {req_id} ...")

        req = fetch_questionnaire(headers, req_id, CLINIC_SLUG)
        if not req:
            safe_print("   ⚠️ No questionnaire data found.")
            continue

        with conn.cursor() as cur:
            insert_questionnaire(cur, req)
            cur.execute(
                "UPDATE pozadavky SET questionnaireprocessed = NOW() WHERE id = %s",
                (req_id,)
            )
            conn.commit()

        time.sleep(0.6)

    conn.close()
    safe_print("\n✅ Done! All questionnaires stored in MySQL table `medevio_questionnaires`.")


if __name__ == "__main__":
    main()