from __future__ import annotations

import argparse
import json
from pathlib import Path

from src.quant_engine.postgresql_history_store_v1 import DOMAIN_TABLES

ROOT = Path(__file__).resolve().parents[1]


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--dsn", required=True)
    ap.add_argument("--out", default=str(ROOT / "Temp" / "postgresql_history_snapshot_v1.json"))
    ap.add_argument("--limit", type=int, default=200)
    args = ap.parse_args()

    try:
        from src.quant_engine.postgresql_history_store_v1 import connect, snapshot_table
    except Exception as exc:
        raise SystemExit(f"import_failed: {exc}")

    conn = connect(args.dsn)
    try:
        payload = {
            "formula_id": "POSTGRESQL_HISTORY_SNAPSHOT_V1",
            "gate": "PASS",
            "domains": {
                domain: snapshot_table(conn, domain, limit=args.limit)
                for domain in DOMAIN_TABLES
            },
        }
    finally:
        conn.close()

    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(payload, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
    print(f"POSTGRESQL_HISTORY_SNAPSHOT_V1 gate=PASS out={out}")
    return 0


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