"""Smoke end-to-end dell'esecuzione REALE su Deribit testnet.

Dimostra il giro completo che serve al live:
  account → OPEN (ordine reale minimo) → VERIFICA posizione su Deribit →
  FEE reale dai trade → CLOSE → VERIFICA flat → riepilogo.

Usa il sizing MINIMO del contratto (BTC $10, ETH $1): costo testnet = €0.
NON tocca il runner: e' solo una prova della macchina di esecuzione.

    uv run python scripts/analysis/live_exec_smoke.py            # ETH + BTC
    uv run python scripts/analysis/live_exec_smoke.py ETH-PERPETUAL
"""
from __future__ import annotations

import sys

from src.live.cerbero_client import CerberoClient
from src.live.execution import ExecutionClient, contract_spec, settlement_currency


def smoke_one(ex: ExecutionClient, instrument: str, notional: float = 10.0) -> bool:
    spec = contract_spec(instrument)
    cur = settlement_currency(instrument)
    kind = "lineare USDC" if spec.get("linear") else "inverse"
    print(f"\n===== {instrument} ({kind}, ~${notional:.0f} notional) =====")

    pre = ex._position_size(instrument)
    print(f"  posizione pre: {pre} USD (atteso 0)")

    print(f"  → OPEN buy ${notional:.0f} notional ...")
    f = ex.open(instrument, "buy", notional, label="smoke-exec")
    print(f"    order_id={f.order_id} state={f.order_state} verified={f.verified}")
    print(f"    fill_price={f.fill_price}  amount={f.amount} ({'BTC' if spec.get('linear') else 'USD'})")
    print(f"    FEE reale: {f.fee_coin:.10f} {cur}  (~${f.fee_usd:.4f})")
    if f.notes:
        print(f"    note: {f.notes}")
    if not f.verified:
        print("    ✗ OPEN NON verificato — interrompo questo strumento")
        return False
    print("    ✓ posizione confermata su Deribit (riletta da get_positions)")

    print("  → CLOSE ...")
    c = ex.close(instrument, label="smoke-exec")
    print(f"    order_id={c.order_id} state={c.order_state} verified(flat)={c.verified}")
    print(f"    fill_price={c.fill_price}  FEE reale: {c.fee_coin:.10f} {cur} (~${c.fee_usd:.4f})")
    if c.notes:
        print(f"    note: {c.notes}")

    post = ex._position_size(instrument)
    ok = f.verified and c.verified and post == 0
    # fee RT reale osservata vs assunto 0.10% RT sul notional
    fee_usd_rt = f.fee_usd + c.fee_usd
    assumed_rt = notional * 0.001
    print(f"    posizione post: {post} USD (atteso 0)")
    print(f"    FEE RT reale ~${fee_usd_rt:.4f} vs assunto 0.10% RT ~${assumed_rt:.4f}")
    print(f"  {'✓ OK' if ok else '✗ FALLITO'} — giro completo {instrument}")
    return ok


def main() -> None:
    instruments = sys.argv[1:] or ["ETH-PERPETUAL", "BTC-PERPETUAL"]
    client = CerberoClient()

    acct = client.get_account_summary(currency="USDC")
    print(f"Account testnet: equity={acct.get('equity')} USDC  testnet={acct.get('testnet')}")
    if not acct.get("testnet"):
        print("✗ ABORT: non e' testnet — niente ordini reali su mainnet.")
        sys.exit(1)

    ex = ExecutionClient(client=client)
    results = {inst: smoke_one(ex, inst) for inst in instruments}

    print("\n===== RIEPILOGO =====")
    for inst, ok in results.items():
        print(f"  {inst:16s} {'✓ OK' if ok else '✗ FALLITO'}")
    sys.exit(0 if all(results.values()) else 1)


if __name__ == "__main__":
    main()
