from __future__ import annotations

import json
from pathlib import Path

import pandas as pd
from pypdf import PdfReader

ROOT = Path(__file__).resolve().parent
errors: list[str] = []
checks: dict[str, object] = {}

audit = pd.read_csv(ROOT / "case-audit.csv")
qual = pd.read_csv(ROOT / "qualitative-cases.csv")

checks["sample_rows"] = len(audit)
checks["region_counts"] = audit["region"].value_counts().to_dict()
checks["case_ids_unique"] = bool(audit["case_id"].is_unique)
checks["valid_tiers"] = bool(set(audit["visibility_tier"]).issubset({"A", "B", "C"}))
checks["binary_values_valid"] = bool(audit.select_dtypes(include="number").isin([0, 1]).all().all())
checks["qualitative_rows"] = len(qual)

if len(audit) != 60:
    errors.append("case-audit.csv must contain exactly 60 rows")
if audit["region"].value_counts().to_dict() != {"北": 15, "中": 15, "南": 15, "東": 15}:
    errors.append("sample must contain 15 cases per region")
if not checks["case_ids_unique"]:
    errors.append("case IDs are not unique")
if not checks["valid_tiers"]:
    errors.append("unknown visibility tier")
if not checks["binary_values_valid"]:
    errors.append("binary fields contain values other than 0/1")

expected_files = [
    "analysis-results.json",
    "paper.md",
    "paper-content.json",
    "paper-metadata.json",
    "paper.pdf",
    "outputs/visibility-tier-summary.csv",
    "outputs/signal-summary.csv",
    "outputs/regional-controlled-summary.csv",
]
expected_files += [f"outputs/figures/figure-{i}-{name}.png" for i, name in [
    (1, "regional-sample"), (2, "visibility-tiers"), (3, "observable-signals"),
    (4, "regional-controlled-channels"), (5, "definition-sensitivity"), (6, "qualitative-matrix")
]]
missing = [name for name in expected_files if not (ROOT / name).exists()]
checks["missing_files"] = missing
if missing:
    errors.append("missing expected files: " + ", ".join(missing))

pdf_path = ROOT / "paper.pdf"
if pdf_path.exists():
    reader = PdfReader(str(pdf_path))
    text = "\n".join(page.extract_text() or "" for page in reader.pages)
    checks["pdf_pages"] = len(reader.pages)
    checks["pdf_searchable_chars"] = len(text)
    checks["pdf_has_title"] = "不是沒有行銷" in text
    if len(text) < 5000:
        errors.append("PDF extracted text is unexpectedly short")
    if not checks["pdf_has_title"]:
        errors.append("PDF title cannot be extracted")

report = {"status": "pass" if not errors else "fail", "checks": checks, "errors": errors}
(ROOT / "validation-report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, ensure_ascii=False, indent=2))
raise SystemExit(1 if errors else 0)
