from __future__ import annotations

import json
from pathlib import Path

from pypdf import PdfReader

ROOT = Path(__file__).resolve().parent
errors: list[str] = []
results = json.loads((ROOT / "analysis-results.json").read_text(encoding="utf-8"))
content = json.loads((ROOT / "paper-content.json").read_text(encoding="utf-8"))
meta = json.loads((ROOT / "paper-metadata.json").read_text(encoding="utf-8"))

def require(condition: bool, message: str) -> None:
    if not condition:
        errors.append(message)

require(content["reportNumber"] == "SHWRP-2026-021", "report number mismatch")
require(content["doi"] == meta["doi"] and meta["doi"].startswith("10.5281/zenodo."), "DOI mismatch or pending")
require(content["version"] == "1.0", "version mismatch")
require(results["industry_count"] == 19, "industry count mismatch")
require(results["vacancy_industry_count"] == 17, "vacancy count mismatch")
require(abs(results["employment_total_change_percent"] - 4.837982) < 0.001, "total employment change mismatch")
require(abs(results["agriculture"]["percent_change"] + 10.948905) < 0.001, "agriculture change mismatch")
require(results["agriculture"]["change_thousand"] == -60, "agriculture employment difference mismatch")
require(results["agriculture"]["share_age_65_plus_2020"] == 48.76, "agriculture age share mismatch")
require(results["mining"]["vacancy_rate"] == 1.5 and results["mining"]["recruitment_months"] == 11.3, "mining vacancy mismatch")

for number in range(1, 7):
    matches = list((ROOT / "outputs" / "figures").glob(f"figure-{number}-*.png"))
    require(len(matches) == 1 and matches[0].stat().st_size > 20_000, f"figure {number} missing or too small")

pdf_path = ROOT / "paper.pdf"
require(pdf_path.exists() and pdf_path.stat().st_size > 100_000, "PDF missing or too small")
if pdf_path.exists():
    reader = PdfReader(str(pdf_path))
    text = "\n".join((page.extract_text() or "") for page in reader.pages)
    require(len(reader.pages) >= 12, "unexpectedly short PDF")
    require(len(text) > 11_000, "PDF text layer too short")
    for phrase in ["SHWRP-2026-021", meta["doi"], "職缺不等於勞動力短缺", "未經外部同儕審查", "第三方權利及授權聲明"]:
        require(phrase in text, f"PDF missing phrase: {phrase}")

for forbidden in ["full_html", "raw_html", "page_text", "full_description", "review_text", "customer_name", "phone", "precise_latitude", "precise_longitude"]:
    for path in ROOT.rglob("*"):
        if path.is_file() and "private" not in path.parts and forbidden in path.name.lower():
            errors.append(f"public-risk filename: {path.relative_to(ROOT)}")

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