from __future__ import annotations
import csv, hashlib, json
from datetime import datetime, timezone
from pathlib import Path
import requests

ROOT = Path(__file__).resolve().parent
URL = "https://apiservice.mol.gov.tw/OdService/download/A17030000J-000016-xC8"
FIELDS = {
    "日期（月別）": "period", "消費者物價-指數": "cpi_index", "消費者物價-年增率": "cpi_yoy_raw",
    "生產者物價-指數": "ppi_index", "生產者物價-年增率": "ppi_yoy_raw",
}

def main():
    response = requests.get(URL, timeout=30); response.raise_for_status(); raw = response.content
    selected = []
    for record in response.json():
        period = str(record.get("日期（月別）", ""))
        if period.startswith(("2025", "2026")):
            selected.append({target: record.get(source, "") for source, target in FIELDS.items()})
    selected.sort(key=lambda row: row["period"])
    output = ROOT / "data" / "labor-ministry-macro-crosscheck.csv"
    with output.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(FIELDS.values()), lineterminator="\n"); writer.writeheader(); writer.writerows(selected)
    attestation = {"sourceUrl": URL, "retrievedAt": datetime.now(timezone.utc).isoformat(), "httpStatus": response.status_code,
        "contentType": response.headers.get("content-type"), "rawResponseBytes": len(raw), "rawResponseSha256": hashlib.sha256(raw).hexdigest(),
        "rawResponseSaved": False, "selectedRows": len(selected), "whitelistedSourceFields": list(FIELDS)}
    (ROOT / "data" / "labor-ministry-fetch-attestation.json").write_text(json.dumps(attestation, ensure_ascii=False, indent=2)+"\n", encoding="utf-8")
    print(json.dumps({"status": "PASSED", **attestation}, ensure_ascii=False))
if __name__ == "__main__": main()
