"""Prepare a small, cited evidence extract from the OECD PISA 2025 report.

This is a transcription of published summary statistics, not a download of
student-level PISA microdata. It validates fields and writes the JSON consumed
by the evidence page. The source CSV preserves the table references and limits.
"""
import csv
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / "evidence/pisa-evidence.csv"
OUTPUT = ROOT / "prototype/src/data/pisa-evidence.json"
TABLES_DIR = ROOT / "evidence/tables"
FIELDS = ("id", "indicator", "value", "unit", "population", "table", "kind", "meaning", "limit")
REQUIRED = set(FIELDS)
TABLE_NUMBERS = ("53", "55", "67", "68", "70")


def prepare(rows):
    prepared = []
    seen = set()
    for row in rows:
        if not REQUIRED.issubset(row):
            raise ValueError("Evidence row is missing a required field")
        if row["id"] in seen:
            raise ValueError("Duplicate evidence ID: " + row["id"])
        seen.add(row["id"])
        value = None if row["value"] == "not reported in chapter text" else float(row["value"])
        prepared.append({**row, "value": value})
    by_id = {row["id"]: row for row in prepared}
    ai = by_id["practice-ai"]["value"]
    online = by_id["practice-online"]["value"]
    if ai is None or online is None:
        raise ValueError("The two classroom-practice figures must be numeric")
    return {
        "title": "PISA 2025 published evidence extract",
        "provenance": "Values transcribed from OECD PISA 2025 Results, Volume I, chapter 4; not student-level microdata.",
        "recordCount": len(prepared),
        "records": prepared,
        "comparison": {
            "aiAssessmentPercent": ai,
            "onlineAssessmentPercent": online,
            "differencePercentagePoints": round(online - ai, 1),
            "interpretation": "The reported opportunity to assess online information is about 20 percentage points more common than the opportunity to assess AI-generated information.",
            "limit": "Both values are approximate OECD averages from self-reports. This is a descriptive comparison, not an effect of the prototype."
        },
        "processing": "CSV rows were checked for required fields and unique IDs; numeric values were converted to numbers. The two classroom-practice figures were subtracted in percentage points. Qualitative findings remain text.",
        "limit": "Descriptive self-reports and associations do not establish that AI use causes learning outcomes or that this prototype changes them."
    }


def main():
    with SOURCE.open(newline="", encoding="utf-8") as file:
        rows = list(csv.DictReader(file))
    report = prepare(rows)
    TABLES_DIR.mkdir(parents=True, exist_ok=True)
    for number in TABLE_NUMBERS:
        subset = [row for row in rows if row["table"].endswith("." + number)]
        if not subset:
            raise ValueError("No records for PISA table " + number)
        with (TABLES_DIR / f"pisa-table-{number}.csv").open("w", newline="", encoding="utf-8") as table_file:
            writer = csv.DictWriter(table_file, fieldnames=FIELDS)
            writer.writeheader()
            writer.writerows(subset)
    OUTPUT.parent.mkdir(parents=True, exist_ok=True)
    OUTPUT.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
    print(f"Prepared {report['recordCount']} cited evidence records in {OUTPUT}")


if __name__ == "__main__":
    main()
