"""Internal consistency checks for SHWRP-2026-013 v0.9."""

from __future__ import annotations

import json
from pathlib import Path

import pandas as pd
from PIL import Image
from pypdf import PdfReader


ROOT = Path(__file__).resolve().parent
OUT = ROOT / "outputs"


def close(a: float, b: float, tol: float = 5e-4) -> None:
    assert abs(a - b) <= tol, f"{a} != {b}"


def main() -> None:
    metadata = json.loads((ROOT / "paper-metadata.json").read_text(encoding="utf-8"))
    assert metadata["reportNumber"] == "SHWRP-2026-013"
    assert metadata["version"] == "1.0"
    assert metadata["doi"] == "10.5281/zenodo.21367949"
    assert metadata["license"] == "CC BY 4.0"

    cpi = pd.read_csv(OUT / "cpi_selected_indices.csv")
    assert len(cpi) == 162
    assert cpi.iloc[0, 0].startswith("2013-01")
    assert cpi.iloc[-1, 0].startswith("2026-06")

    corr = pd.read_csv(OUT / "rice_price_correlations.csv")
    chicken = corr.set_index("product").loc["雞肉"]
    oil = corr.set_index("product").loc["食用油"]
    pork = corr.set_index("product").loc["豬肉"]
    close(chicken.pearson_yoy, 0.3235695992)
    close(oil.pearson_yoy, 0.2537220465)
    close(pork.pearson_yoy, 0.1439595984)
    assert corr.iloc[0]["product"] == "雞肉"

    prepared = pd.read_csv(OUT / "prepared_rice_food_models.csv").set_index("product")
    close(prepared.loc["豬肉", "beta"], 0.1863792157)
    close(prepared.loc["米", "beta"], 0.0090701983)
    assert prepared.loc["豬肉", "ci_low"] > 0
    assert prepared.loc["米", "ci_low"] < 0 < prepared.loc["米", "ci_high"]

    festival = pd.read_csv(OUT / "festival_month_models.csv").set_index("product")
    assert (festival.ci_low < 0).all() and (festival.ci_high > 0).all()
    close(festival.loc["水果", "beta"], 1.10248256)
    close(festival.loc["豬肉", "beta"], -0.2563347773)

    hog = json.loads((OUT / "hog_event_summary.json").read_text(encoding="utf-8"))
    close(hog["current_july"]["weighted_price"], 101.8030675745)
    close(hog["same_period_2025"]["weighted_price"], 104.3305721128)
    close(hog["jan_may_2026"]["weighted_price"], 85.6951778114)
    assert hog["data_end"] == "2026-07-14"
    assert hog["latest_heads"] == 17519

    for number in range(1, 6):
        chart = next((OUT / "figures").glob(f"fig{number}_*.png"))
        with Image.open(chart) as image:
            assert image.width >= 1500 and image.height >= 900

    reader = PdfReader(ROOT / "paper.pdf")
    assert len(reader.pages) == 14
    page_texts = [page.extract_text() or "" for page in reader.pages]
    full_text = "\n".join(page_texts)
    assert min(map(len, page_texts)) > 300
    for phrase in [
        "哪些農產品與米最有關",
        "101.80",
        "0.186",
        "研究揭露與作者責任",
        "參考文獻與資料來源",
    ]:
        assert phrase in full_text, phrase

    checks = {
        "report": metadata["reportNumber"],
        "version": metadata["version"],
        "cpi_months": len(cpi),
        "hog_data_end": hog["data_end"],
        "pdf_pages": len(reader.pages),
        "pdf_searchable_characters": len(full_text),
        "figures": 5,
        "result": "pass",
    }
    (ROOT / "validation-report.json").write_text(json.dumps(checks, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(checks, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
