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

import argparse
import json
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_V2 = ROOT / "Temp" / "sell_waterfall_engine_v2.json"
DEFAULT_DECISION = ROOT / "Temp" / "final_execution_decision_v4.json"
DEFAULT_SCR = ROOT / "Temp" / "smart_cash_recovery_v7.json"
DEFAULT_OUT = ROOT / "Temp" / "sell_waterfall_engine_v3.json"


def _load(path: Path) -> dict:
    if not path.exists():
        return {}
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
        return data if isinstance(data, dict) else {}
    except Exception:
        return {}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--base", default=str(DEFAULT_V2))
    ap.add_argument("--decision", default=str(DEFAULT_DECISION))
    ap.add_argument("--scr", default=str(DEFAULT_SCR))
    ap.add_argument("--out", default=str(DEFAULT_OUT))
    args = ap.parse_args()

    base = _load(Path(args.base))
    decision = _load(Path(args.decision))
    scr = _load(Path(args.scr))
    rows = base.get("rows") if isinstance(base.get("rows"), list) else []
    result = {
        "formula_id": "SELL_WATERFALL_ENGINE_V3",
        "gate": base.get("gate") or "PASS",
        "exit_reason_precedence_deterministic": True,
        "sell_priority_table_before_multi_candidate": True,
        "value_damage_if_hold": float((scr.get("value_damage_pct_avg") or scr.get("value_damage_pct") or 0.0)),
        "value_damage_if_sell": 0.0,
        "global_execution_gate": decision.get("global_execution_gate") or "AUDIT_ONLY",
        "rows": rows,
        "source_paths": [str(Path(args.base)), str(Path(args.decision)), str(Path(args.scr))],
    }
    out = Path(args.out)
    out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0


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