from __future__ import annotations

import csv
import hashlib
import json
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "data/input/tunisia_source_aligned_quarterly_panel.csv"
CANONICAL = ROOT / "data/input/tunisia_aligned_quarterly_panel.csv"
REPORT = ROOT / "outputs/logs/source_projection_verification.json"

subprocess.run(
    [sys.executable, str(ROOT / "scripts/prepare_analysis_input.py"), "--check"],
    cwd=ROOT,
    check=True,
)

with SOURCE.open(newline="", encoding="utf-8-sig") as handle:
    source_rows = list(csv.DictReader(handle))
with CANONICAL.open(newline="", encoding="utf-8-sig") as handle:
    canonical_rows = list(csv.DictReader(handle))

sha256 = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
report = {
    "status": "PASS",
    "source_file": str(SOURCE.relative_to(ROOT)),
    "source_sha256": sha256(SOURCE),
    "canonical_file": str(CANONICAL.relative_to(ROOT)),
    "canonical_sha256": sha256(CANONICAL),
    "rows": len(source_rows),
    "quarter_start": source_rows[0]["quarter"],
    "quarter_end": source_rows[-1]["quarter"],
    "core_coordinates": ["trust_obs", "shock_obs", "policy_proxy"],
    "projection_rule": {
        "quarter": "quarter",
        "year": "year_decimal",
        "quarter_index": "zero-based row index",
        "trust_obs": "trust_obs",
        "shock_obs": "shock_obs",
        "policy_proxy": "policy_proxy"
    },
    "note": "The canonical six-column input is an exact textual field projection of the deposited author-supplied source-aligned panel; no digitisation, interpolation, rounding, or estimation is applied."
}
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text(json.dumps(report, indent=2), encoding="utf-8")
print("Source-file verification PASS.")
