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

"""
Download all attachments for pozadavky where attachmentsProcessed IS NULL
Store them in MySQL table `medevio_downloads` on 192.168.1.50.
"""

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

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


# ==============================
# 🛡 SAFE PRINT
# ==============================
def safe_print(text: str):
    enc = sys.stdout.encoding or ""
    if not enc or 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 (.50)
# ==============================
TOKEN_PATH = Path(__file__).resolve().parent.parent / "token.txt"
CLINIC_SLUG = "mudr-buzalkova"

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

CREATED_AFTER = "2024-12-01"

GRAPHQL_QUERY = r"""
query ClinicRequestDetail_GetPatientRequest2($requestId: UUID!) {
  patientRequestMedicalRecords: listMedicalRecordsForPatientRequest(
    attachmentTypes: [ECRF_FILL_ATTACHMENT, MESSAGE_ATTACHMENT, PATIENT_REQUEST_ATTACHMENT]
    patientRequestId: $requestId
    pageInfo: {first: 100, offset: 0}
  ) {
    attachmentType
    id
    medicalRecord {
      contentType
      description
      downloadUrl
      id
      url
      visibleToPatient
    }
  }
}
"""


def extract_filename_from_url(url: str) -> str:
    try:
        return url.split("/")[-1].split("?")[0]
    except:
        return "unknown_filename"


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


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

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

    safe_print(f"✅ V databázi již máme {len(existing_ids)} příloh.")

    # 2. Výběr požadavků ke zpracování
    sql = "SELECT id, pacient_prijmeni, pacient_jmeno, createdAt FROM pozadavky WHERE attachmentsProcessed IS NULL"
    params = []
    if CREATED_AFTER:
        sql += " AND createdAt >= %s"
        params.append(CREATED_AFTER)

    with conn.cursor() as cur:
        cur.execute(sql, params)
        req_rows = cur.fetchall()

    safe_print(f"📋 Počet požadavků ke stažení příloh: {len(req_rows)}")

    for i, row in enumerate(req_rows, 1):
        req_id = row["id"]
        prijmeni = row.get("pacient_prijmeni") or "Neznamy"
        created_date = row.get("createdAt") or datetime.now()

        safe_print(f"\n[{i}/{len(req_rows)}] 🧾 {prijmeni} ({req_id})")

        payload = {
            "operationName": "ClinicRequestDetail_GetPatientRequest2",
            "query": GRAPHQL_QUERY,
            "variables": {"requestId": req_id},
        }

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

            if attachments:
                with conn.cursor() as cur:
                    for a in attachments:
                        m = a.get("medicalRecord") or {}
                        att_id = a.get("id")

                        if att_id in existing_ids:
                            continue

                        url = m.get("downloadUrl")
                        if url:
                            att_r = requests.get(url, timeout=30)
                            if att_r.status_code == 200:
                                content = att_r.content
                                filename = extract_filename_from_url(url)

                                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, att_id, a.get("attachmentType"), filename,
                                      m.get("contentType"), len(content), created_date, content))
                                existing_ids.add(att_id)
                                safe_print(f"   💾 Uloženo: {filename} ({len(content) / 1024:.1f} kB)")

                conn.commit()

            # Označíme jako zpracované i když nebyly nalezeny žádné přílohy
            with conn.cursor() as cur:
                cur.execute("UPDATE pozadavky SET attachmentsProcessed = 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()
    safe_print("\n🎯 Všechny přílohy byly zpracovány.")


if __name__ == "__main__":
    main()