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


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

# UTF-8 SAFE OUTPUT
try:
    sys.stdout.reconfigure(encoding='utf-8')
    sys.stderr.reconfigure(encoding='utf-8')
except AttributeError:
    pass

# ==============================
# CONFIG (.50)
# ==============================
TOKEN_PATH = Path(__file__).resolve().parent.parent / "token.txt"

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

GRAPHQL_QUERY_MESSAGES = r"""
query UseMessages_ListMessages($requestId: String!, $updatedSince: DateTime) {
  messages: listMessages(patientRequestId: $requestId, updatedSince: $updatedSince) {
    id createdAt updatedAt readAt text type
    sender { id name surname clinicId }
    medicalRecord { id description contentType url downloadUrl createdAt updatedAt }
  }
}
"""

def parse_dt(s):
    if not s: return None
    try: return datetime.fromisoformat(s.replace("Z", "+00:00"))
    except: return None

def read_token(path: Path) -> str:
    return path.read_text(encoding="utf-8").strip().replace("Bearer ", "")

def main():
    token = read_token(TOKEN_PATH)
    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    conn = pymysql.connect(**DB_CONFIG)

    # 1. Seznam již stažených příloh (prevence duplicit)
    with conn.cursor() as cur:
        cur.execute("SELECT attachment_id FROM medevio_downloads")
        existing_ids = {r["attachment_id"] for r in cur.fetchall()}

    # 2. Seznam požadavků k synchronizaci
    with conn.cursor() as cur:
        cur.execute("""
            SELECT id, messagesProcessed FROM pozadavky
            WHERE messagesProcessed IS NULL OR messagesProcessed < updatedAt
        """)
        rows = cur.fetchall()

    print(f"📋 Počet požadavků k synchronizaci zpráv: {len(rows)}")

    for i, row in enumerate(rows, 1):
        req_id = row["id"]
        updated_since = row["messagesProcessed"]
        if updated_since:
            updated_since = updated_since.replace(microsecond=0).isoformat() + "Z"

        print(f"[{i}/{len(rows)}] Synchronizuji: {req_id}")

        payload = {
            "operationName": "UseMessages_ListMessages",
            "query": GRAPHQL_QUERY_MESSAGES,
            "variables": {"requestId": req_id, "updatedSince": updated_since}
        }

        try:
            r = requests.post("https://api.medevio.cz/graphql", json=payload, headers=headers, timeout=30)
            messages = r.json().get("data", {}).get("messages", []) or []

            if messages:
                with conn.cursor() as cur:
                    for msg in messages:
                        # Uložení zprávy
                        sender = msg.get("sender") or {}
                        sender_name = " ".join(filter(None, [sender.get("name"), sender.get("surname")]))
                        mr = msg.get("medicalRecord") or {}

                        cur.execute("""
                            INSERT INTO medevio_conversation (
                                id, request_id, sender_name, sender_id, sender_clinic_id,
                                text, created_at, read_at, updated_at,
                                attachment_url, attachment_description, attachment_content_type
                            ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
                            ON DUPLICATE KEY UPDATE
                                text = VALUES(text), updated_at = VALUES(updated_at), read_at = VALUES(read_at)
                        """, (
                            msg.get("id"), req_id, sender_name, sender.get("id"), sender.get("clinicId"),
                            msg.get("text"), parse_dt(msg.get("createdAt")), parse_dt(msg.get("readAt")),
                            parse_dt(msg.get("updatedAt")), mr.get("downloadUrl") or mr.get("url"),
                            mr.get("description"), mr.get("contentType")
                        ))

                        # Uložení přílohy (pokud existuje a nemáme ji)
                        attachment_id = mr.get("id")
                        if attachment_id and attachment_id not in existing_ids:
                            url = mr.get("downloadUrl") or mr.get("url")
                            if url:
                                att_r = requests.get(url, timeout=30)
                                if att_r.status_code == 200:
                                    cur.execute("""
                                        INSERT INTO medevio_downloads (
                                            request_id, attachment_id, attachment_type,
                                            filename, content_type, file_size, created_at, file_content
                                        ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)
                                    """, (
                                        req_id, attachment_id, "MESSAGE_ATTACHMENT",
                                        url.split("/")[-1].split("?")[0], mr.get("contentType"),
                                        len(att_r.content), parse_dt(msg.get("createdAt")), att_r.content
                                    ))
                                    existing_ids.add(attachment_id)

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

            time.sleep(0.3)
        except Exception as e:
            print(f"   ❌ Chyba u {req_id}: {e}")

    conn.close()
    print("\n🎉 Delta sync zpráv a příloh DOKONČEN")

if __name__ == "__main__":
    main()