#!/usr/bin/env python3
from __future__ import annotations

import argparse
import datetime as dt
import json
from pathlib import Path
from typing import Any

import numpy as np


SCRIPT_VERSION = "check_paper_live_freshness_v1_2026_05_05"


def iso(ts: int | float) -> str:
    return dt.datetime.fromtimestamp(float(ts), tz=dt.timezone.utc).isoformat().replace("+00:00", "Z")


def read_npz_meta(path: Path) -> dict[str, Any]:
    z = np.load(path, allow_pickle=False)
    meta: dict[str, Any] = {}
    if "meta_json" in z.files:
        meta = json.loads(str(z["meta_json"]))
    ts = z["ts"] if "ts" in z.files else np.array([], dtype=np.int64)
    return {
        "meta": meta,
        "events": int(len(ts)),
        "first_event_ts": int(ts[0]) if len(ts) else None,
        "last_event_ts": int(ts[-1]) if len(ts) else None,
    }


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--npz", required=True, help="Watched NPZ path")
    ap.add_argument("--out-md", required=True, help="Markdown report path")
    ap.add_argument("--max-stale-hours", type=float, default=6.0)
    ap.add_argument("--now-ts", type=float, default=0.0, help="Override current epoch seconds for tests")
    args = ap.parse_args()

    now = float(args.now_ts) if args.now_ts else dt.datetime.now(dt.timezone.utc).timestamp()
    npz = Path(args.npz)
    out_md = Path(args.out_md)
    out_md.parent.mkdir(parents=True, exist_ok=True)

    status = "missing"
    details: dict[str, Any] = {
        "script_version": SCRIPT_VERSION,
        "npz": str(npz),
        "current_utc": iso(now),
        "max_stale_hours": float(args.max_stale_hours),
    }

    if npz.exists():
        info = read_npz_meta(npz)
        st = npz.stat()
        last_ts = info["last_event_ts"]
        stale_hours = (now - float(last_ts)) / 3600.0 if last_ts is not None else None
        status = "fresh" if stale_hours is not None and stale_hours <= args.max_stale_hours else "stale"
        meta = info["meta"]
        details.update({
            "npz_mtime_utc": iso(st.st_mtime),
            "events": info["events"],
            "first_event_utc": iso(info["first_event_ts"]) if info["first_event_ts"] is not None else "",
            "last_event_utc": iso(last_ts) if last_ts is not None else "",
            "stale_hours": stale_hours,
            "pool_name": meta.get("pool_name", ""),
            "fee_rate": meta.get("fee_rate", ""),
            "input_usd_sum": meta.get("input_usd_sum", ""),
            "price_start": meta.get("price_start", ""),
            "price_end": meta.get("price_end", ""),
        })

    report = [
        "# Paper-Live Freshness Check",
        "",
        f"status: `{status}`",
        "",
        "```json",
        json.dumps(details, indent=2, ensure_ascii=False, sort_keys=True),
        "```",
        "",
    ]
    if status == "fresh":
        report.append("Result: watched NPZ is fresh enough for paper-live decision checks.")
    elif status == "stale":
        report.append("Result: watched NPZ is stale; paper-live watcher health is not live-market proof.")
    else:
        report.append("Result: watched NPZ is missing; paper-live watcher cannot prove live-market behavior.")
    out_md.write_text("\n".join(report) + "\n", encoding="utf-8")
    print(json.dumps({"status": status, "report": str(out_md), **details}, indent=2, ensure_ascii=False, sort_keys=True))
    return 0 if status == "fresh" else 10


if __name__ == "__main__":
    raise SystemExit(main())
