#!/usr/bin/env python3
"""
Allocate IV-engine sleeve reference risk onto legacy4 JSONL rows so portfolio merge
uses the same R_put / R_rr as ``engine_iv_*_ivx1.jsonl`` (sum of broker_risk_usd).

Each legacy trade gets::

    broker_risk_usd = R_iv_engine / n_legacy_trades

so ``sum(broker_risk_usd) == R_iv_engine`` and ``--capital-*-pct`` from the IV Sharpe/DD
search applies with the **same C/R** as the full IV overlay run, while **pnl_total**
stays the literature 1-lot stream.

This is a deliberate bridge (not physical margin per trade); see ``bridge_note`` on
each row.
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

_REPO = Path(__file__).resolve().parents[2]
if str(_REPO) not in sys.path:
    sys.path.insert(0, str(_REPO))

from RenTech.strategy_stack.portfolio_vrp_plus_vxx import (  # noqa: E402
    _infer_broker_risk_overlay,
    _overlay_sleeve_risk_reference_usd,
)

_LOGS = _REPO / "RenTech" / "data" / "logs"


def _load_jsonl(path: Path) -> list[dict]:
    rows: list[dict] = []
    with path.open(encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            rows.append(json.loads(line))
    return rows


def _write_jsonl(path: Path, rows: list[dict]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as f:
        for r in rows:
            f.write(json.dumps(r, separators=(",", ":"), default=str) + "\n")


def _bridge_one(
    *,
    legacy_path: Path,
    iv_engine_path: Path,
    out_path: Path,
    sleeve: str,
) -> dict:
    iv_ref = float(_overlay_sleeve_risk_reference_usd(iv_engine_path, _infer_broker_risk_overlay))
    rows = _load_jsonl(legacy_path)
    n = len(rows)
    if n <= 0:
        raise SystemExit(f"No rows in {legacy_path}")
    per = iv_ref / float(n)
    out: list[dict] = []
    for r in rows:
        d = dict(r)
        d["contracts"] = 1
        d["broker_risk_usd"] = per
        d["broker_risk_per_contract_usd"] = per
        d["bridge_note"] = (
            f"{sleeve}: uniform broker_risk_usd so sum matches IV engine sleeve ref "
            f"({iv_ref:,.2f} USD over {n} trades → {per:,.6f} per row)"
        )
        d["bridge_iv_engine_jsonl"] = str(iv_engine_path.as_posix())
        d["bridge_iv_engine_risk_ref_usd"] = iv_ref
        out.append(d)
    _write_jsonl(out_path, out)
    return {
        "sleeve": sleeve,
        "legacy_path": str(legacy_path),
        "iv_engine_path": str(iv_engine_path),
        "out_path": str(out_path),
        "iv_engine_risk_ref_usd": iv_ref,
        "n_legacy_trades": n,
        "broker_risk_usd_per_row": per,
    }


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument(
        "--legacy-put",
        type=Path,
        default=_LOGS / "legacy4_put_overlay.jsonl",
    )
    ap.add_argument(
        "--legacy-rr",
        type=Path,
        default=_LOGS / "legacy4_rr_overlay.jsonl",
    )
    ap.add_argument(
        "--iv-put",
        type=Path,
        default=_LOGS / "engine_iv_otm_put_ivx1.jsonl",
    )
    ap.add_argument(
        "--iv-rr",
        type=Path,
        default=_LOGS / "engine_iv_risk_reversal_ivx1.jsonl",
    )
    ap.add_argument(
        "--out-put",
        type=Path,
        default=_LOGS / "legacy4_put_overlay_ivbridged.jsonl",
    )
    ap.add_argument(
        "--out-rr",
        type=Path,
        default=_LOGS / "legacy4_rr_overlay_ivbridged.jsonl",
    )
    ap.add_argument(
        "--meta-json",
        type=Path,
        default=_LOGS / "legacy4_ivbridge_meta.json",
    )
    args = ap.parse_args()

    rep: list[dict] = []
    rep.append(_bridge_one(legacy_path=args.legacy_put, iv_engine_path=args.iv_put, out_path=args.out_put, sleeve="put"))
    rep.append(_bridge_one(legacy_path=args.legacy_rr, iv_engine_path=args.iv_rr, out_path=args.out_rr, sleeve="risk_reversal"))
    args.meta_json.parent.mkdir(parents=True, exist_ok=True)
    args.meta_json.write_text(json.dumps(rep, indent=2), encoding="utf-8")
    print(json.dumps(rep, indent=2))
    print(f"\nWrote {args.out_put}\nWrote {args.out_rr}\nWrote {args.meta_json}", flush=True)


if __name__ == "__main__":
    main()
