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

"""
Fetch communication threads (messages) from Medevio API
for pozadavky where communicationprocessed IS NULL or outdated,
optionally filtered by creation date.
Stores results in MySQL table `medevio_messages`.
"""

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

# ==============================
# 🔧 CONFIGURATION
# ==============================
TOKEN_PATH = Path(__file__).resolve().parent.parent / "token.txt"
GRAPHQL_URL = "https://api.medevio.cz/graphql"

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

# ✅ Optional: Only process requests created after this date
# Leave empty ("") to process all
CREATED_AFTER = "2025-11-09"   # 🕓 Adjust freely, or set to "" for no limit

# ==============================
# 🔐 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


headers = {
    "Authorization": f"Bearer {read_token(TOKEN_PATH)}",
    "Content-Type": "application/json",
}

# ==============================
# 🧩 GRAPHQL QUERY
# ==============================
GRAPHQL_QUERY = """
query UseMessages_ListMessages($requestId: String!, $updatedSince: DateTime) {
  messages: listMessages(
    patientRequestId: $requestId
    updatedSince: $updatedSince
  ) {
    id
    createdAt
    text
    updatedAt
    readAt
    sender { id name surname clinicId }
    medicalRecord { downloadUrl description contentType }
  }
}
"""

# ==============================
# 🧮 HELPERS
# ==============================
def normalize_ts(ts: str):
    """Convert ISO 8601 string to MySQL DATETIME format."""
    if not ts:
        return None
    ts = ts.replace("T", " ").replace("Z", "")
    if "." in ts:
        ts = ts.split(".")[0]
    return ts


# ==============================
# 📡 FETCH MESSAGES
# ==============================
def fetch_messages(request_id):
    payload = {
        "operationName": "UseMessages_ListMessages",
        "variables": {"requestId": request_id, "updatedSince": None},
        "query": GRAPHQL_QUERY,
    }
    r = requests.post(GRAPHQL_URL, headers=headers, json=payload, timeout=30)
    if r.status_code != 200:
        print(f"❌ HTTP {r.status_code}: {r.text}")
        return []
    return r.json().get("data", {}).get("messages", []) or []


# ==============================
# 💾 CREATE TABLE IF NEEDED
# ==============================
def ensure_table_exists(conn):
    with conn.cursor() as cur:
        cur.execute("""
        CREATE TABLE IF NOT EXISTS medevio_messages (
            id VARCHAR(64) PRIMARY KEY,
            request_id VARCHAR(64),
            sender_name VARCHAR(255),
            sender_id VARCHAR(64),
            sender_clinic_id VARCHAR(64),
            text TEXT,
            created_at DATETIME NULL,
            read_at DATETIME NULL,
            updated_at DATETIME NULL,
            attachment_url TEXT,
            attachment_description TEXT,
            attachment_content_type VARCHAR(128),
            inserted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        ) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
        """)
    conn.commit()


# ==============================
# 💾 INSERT MESSAGE
# ==============================
def insert_message(cur, req_id, msg):
    sender = msg.get("sender") or {}
    medrec = msg.get("medicalRecord") or {}

    cur.execute("""
        REPLACE INTO medevio_messages (
            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)
    """, (
        msg.get("id"),
        req_id,
        f"{sender.get('name','')} {sender.get('surname','')}".strip(),
        sender.get("id"),
        sender.get("clinicId"),
        msg.get("text"),
        normalize_ts(msg.get("createdAt")),
        normalize_ts(msg.get("readAt")),
        normalize_ts(msg.get("updatedAt")),
        medrec.get("downloadUrl"),
        medrec.get("description"),
        medrec.get("contentType")
    ))


# ==============================
# 🧠 MAIN
# ==============================
def main():
    conn = pymysql.connect(**DB_CONFIG)
    ensure_table_exists(conn)

    with conn.cursor() as cur:
        sql = """
            SELECT id, createdAt, updatedAt, communicationprocessed
            FROM pozadavky
            WHERE (communicationprocessed IS NULL OR communicationprocessed < updatedAt)
        """
        if CREATED_AFTER:
            sql += " AND createdAt >= %s"
            cur.execute(sql, (CREATED_AFTER,))
        else:
            cur.execute(sql)

        rows = cur.fetchall()

    if not rows:
        print("✅ No pending communication updates.")
        return

    print(f"📋 Found {len(rows)} requests needing communication check.")

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

        messages = fetch_messages(req_id)
        print(f"   💬 {len(messages)} messages found.")

        # Update timestamp even if none found
        with conn.cursor() as cur:
            if messages:
                for msg in messages:
                    insert_message(cur, req_id, msg)
            cur.execute("""
                UPDATE pozadavky
                SET communicationprocessed = NOW()
                WHERE id = %s
            """, (req_id,))
            conn.commit()

        print(f"   ✅ Processed {len(messages)} messages for {req_id}")
        time.sleep(0.5)  # avoid hammering the API

    conn.close()
    print("\n✅ All communication threads processed and timestamps updated.")


# ==============================
if __name__ == "__main__":
    main()
