from __future__ import annotations

import csv
import hashlib
import json
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "app" / "data" / "official_imports"


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def profile_rpl(path: Path) -> dict:
    total = human = skipped = rejected = variants = with_gtin = 0
    required = {
        "Identyfikator Produktu Leczniczego",
        "Nazwa Produktu Leczniczego",
        "Rodzaj preparatu",
        "Opakowanie",
        "Numer pozwolenia",
    }
    with path.open("r", encoding="utf-8-sig", newline="") as handle:
        reader = csv.DictReader(handle, delimiter=";", quotechar='"')
        missing = sorted(required - set(reader.fieldnames or []))
        if missing:
            raise RuntimeError(f"RPL missing columns: {missing}")
        for row in reader:
            total += 1
            kind = (row.get("Rodzaj preparatu") or "").strip().lower()
            if kind and "ludzki" not in kind:
                skipped += 1
                continue
            product_id = (row.get("Identyfikator Produktu Leczniczego") or "").strip()
            name = (row.get("Nazwa Produktu Leczniczego") or "").strip()
            if not product_id or not name:
                rejected += 1
                continue
            human += 1
            gtins = set(re.findall(r"(?<!\d)(\d{13,14})(?!\d)", row.get("Opakowanie") or ""))
            if gtins:
                with_gtin += 1
                variants += len(gtins)
            else:
                variants += 1
    return {
        "rows": total,
        "human_products": human,
        "non_human_skipped": skipped,
        "rejected": rejected,
        "products_with_gtin": with_gtin,
        "expected_variant_rows": variants,
    }


def profile_rhf(path: Path) -> dict:
    total = active = inactive = blank_names = 0
    ids: set[str] = set()
    required = {
        "hurtownia_unikalneId",
        "hurtownia_status",
        "hurtownia_nazwa",
        "właściciel_1_nazwa",
        "zezwolenie_nrZezwolenia",
    }
    with path.open("r", encoding="utf-8-sig", newline="") as handle:
        reader = csv.DictReader(handle, delimiter=";", quotechar='"')
        missing = sorted(required - set(reader.fieldnames or []))
        if missing:
            raise RuntimeError(f"RHF missing columns: {missing}")
        for row in reader:
            total += 1
            unique_id = (row.get("hurtownia_unikalneId") or "").strip()
            if unique_id:
                ids.add(unique_id)
            if (row.get("hurtownia_status") or "").strip().lower() == "aktywna":
                active += 1
            else:
                inactive += 1
            if not ((row.get("hurtownia_nazwa") or "").strip() or (row.get("właściciel_1_nazwa") or "").strip()):
                blank_names += 1
    return {
        "rows": total,
        "unique_registry_ids": len(ids),
        "active": active,
        "inactive_or_other": inactive,
        "blank_display_sources": blank_names,
    }


rpl = DATA / "Rejestr_Produktow_Leczniczych_20260713.csv"
rhf = DATA / "Rejestr_Hurtowni_Farmaceutycznych_20260713.csv"
profile = {
    "data_date": "2026-07-13",
    "rpl": profile_rpl(rpl) | {"bytes": rpl.stat().st_size, "sha256": sha256(rpl)},
    "rhf": profile_rhf(rhf) | {"bytes": rhf.stat().st_size, "sha256": sha256(rhf)},
    "safety": {
        "automatic_prescribing": False,
        "automatic_ordering": False,
        "local_formulary_approval_required": True,
        "local_supplier_contract_approval_required": True,
    },
}
(DATA / "IMPORT_DATA_PROFILE.json").write_text(json.dumps(profile, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps(profile, ensure_ascii=False, indent=2))
