import requests
import json
from pathlib import Path

# === Nastavení ===
TOKEN_PATH = Path(__file__).resolve().parent.parent / "token.txt"
REQUEST_ID = "092a0c63-28be-4c6b-ab3b-204e1e2641d4"
OUTPUT_DIR = Path(r"u:\Dropbox\!!!Days\Downloads Z230\Medevio_přílohy")

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

GRAPHQL_QUERY = r"""
query ClinicRequestDetail_GetPatientRequest2(
  $requestId: UUID!,
  $isDoctor: Boolean!
) {
  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 @include(if: $isDoctor)
    }
  }
}
"""

variables = {
    "isDoctor": True,
    "requestId": REQUEST_ID,
}

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

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

print("📡 Querying Medevio API for attachments...\n")
r = requests.post("https://api.medevio.cz/graphql", json=payload, headers=headers)
print(f"HTTP status: {r.status_code}\n")

data = r.json()
records = data.get("data", {}).get("patientRequestMedicalRecords", [])
if not records:
    print("⚠️ No attachments found.")
    exit()

# === Uložení ===
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
print(f"📂 Saving {len(records)} attachments to: {OUTPUT_DIR}\n")

for rec in records:
    med = rec.get("medicalRecord", {})
    url = med.get("downloadUrl")
    name = med.get("description", med.get("id")) or "unknown.pdf"

    if not url:
        print(f"❌ Skipped {name} (no download URL)")
        continue

    safe_name = name.replace("/", "_").replace("\\", "_")
    out_path = OUTPUT_DIR / safe_name

    print(f"⬇️  Downloading: {safe_name}")
    try:
        file_data = requests.get(url, timeout=30)
        file_data.raise_for_status()
        out_path.write_bytes(file_data.content)
        print(f"✅ Saved: {out_path.name} ({len(file_data.content)/1024:.1f} KB)")
    except Exception as e:
        print(f"❌ Error saving {safe_name}: {e}")

print("\n🎉 Done!")
