"""
CV6 AI Trading OS — Integration Fix Verification
Tests MM-01 (Dashboard PnL), MM-02 (Portfolio Funds), MM-03 (Trade History)
Run AFTER restarting the backend.
"""
import requests, json, sys

BASE = "http://127.0.0.1:8000"
PASS = "✅ PASS"
FAIL = "❌ FAIL"

results = []

def check(label, got, expected_fn, note=""):
    ok = expected_fn(got)
    status = PASS if ok else FAIL
    results.append((status, label, got, note))
    print(f"{status}  {label}: {got}  {note}")
    return ok

# ── Auth ──────────────────────────────────────────────────────────────
print("\n=== STEP 1: Login ===")
r = requests.post(f"{BASE}/users/login",
    json={"email": "psasi144@gmail.com", "password": "CV6Tr@d3r2026!"})
if r.status_code != 200:
    print(f"Login failed: {r.status_code} {r.text}")
    sys.exit(1)
token = r.json()["access_token"]
headers = {"Authorization": f"Bearer {token}"}
print(f"JWT obtained ✅")

# ── Reset paper account to clean state ───────────────────────────────
print("\n=== STEP 2: Reset Paper Account ===")
r = requests.post(f"{BASE}/paper/reset?capital=100000", headers=headers)
print(f"Reset: {r.status_code} {r.json().get('message','')}")

# ── Execute 3 BUY → SELL pairs ───────────────────────────────────────
print("\n=== STEP 3: Execute 3 BUY→SELL pairs ===")
trades = [
    ("NIFTY",    "BUY",  1, 24350.0),
    ("NIFTY",    "SELL", 1, 24450.0),  # PnL = +100
    ("TCS",      "BUY",  5,  3820.0),
    ("TCS",      "SELL", 5,  3860.0),  # PnL = +200
    ("RELIANCE", "BUY",  5,  2960.0),
    ("RELIANCE", "SELL", 5,  2990.0),  # PnL = +150
]
expected_pnl = 100 + 200 + 150  # = 450

sell_count = 0
for sym, action, qty, price in trades:
    r = requests.post(f"{BASE}/paper/trade", headers=headers, json={
        "symbol": sym, "action": action, "quantity": qty,
        "entry_price": price, "capital": 100000,
    })
    data = r.json()
    if action == "SELL" and data.get("success"):
        sell_count += 1
    print(f"  {action} {qty}x {sym} @ {price}: {data.get('message','')[:60]}")

print(f"Completed SELLs: {sell_count}/3")

# ── TEST 1: Paper account PnL ────────────────────────────────────────
print("\n=== TEST 1: Paper Account PnL ===")
r = requests.get(f"{BASE}/paper/account", headers=headers)
acc = r.json()
paper_pnl = acc.get("realized_pnl", -999)
check("paper_account.realized_pnl", paper_pnl,
      lambda v: abs(v - expected_pnl) < 0.01,
      f"(expected {expected_pnl})")

# ── TEST 2: Dashboard PnL (MM-01) ────────────────────────────────────
print("\n=== TEST 2: Dashboard PnL (MM-01 fix) ===")
r = requests.get(f"{BASE}/dashboard/pnl", headers=headers)
dash_pnl_data = r.json()
dash_pnl = dash_pnl_data.get("realized_pnl", -999)
check("dashboard/pnl.realized_pnl", dash_pnl,
      lambda v: abs(v - expected_pnl) < 0.01,
      f"(expected {expected_pnl}, was 0 before fix)")

# ── TEST 3: Dashboard Funds (MM-02) ──────────────────────────────────
print("\n=== TEST 3: Dashboard Funds (MM-02 fix) ===")
r = requests.get(f"{BASE}/dashboard/funds", headers=headers)
funds = r.json()
avail = funds.get("available_cash", -999)
total = funds.get("total_funds", -999)
check("dashboard/funds.available_cash", avail,
      lambda v: v > 0,
      f"(expected >0, was 0 before fix)")
check("dashboard/funds.total_funds", total,
      lambda v: v > 0,
      f"(expected >0, was 0 before fix)")
check("dashboard/funds.broker", funds.get("broker", ""),
      lambda v: v == "paper",
      "(expected 'paper')")

# ── TEST 4: Trade History SQLite (MM-03) ─────────────────────────────
print("\n=== TEST 4: Trade History SQLite (MM-03 fix) ===")
r = requests.get(f"{BASE}/history/", headers=headers)
hist = r.json()
trade_count = hist.get("total", len(hist.get("trades", [])))
check("history/.total", trade_count,
      lambda v: v >= 3,
      f"(expected >=3 paper trades, was 0 before fix)")

# ── TEST 5: History PnL (MM-03 secondary) ────────────────────────────
print("\n=== TEST 5: History PnL Summary ===")
r = requests.get(f"{BASE}/history/pnl", headers=headers)
hpnl = r.json()
hist_pnl = hpnl.get("total_pnl", -999)
check("history/pnl.total_pnl", hist_pnl,
      lambda v: abs(v - expected_pnl) < 0.01,
      f"(expected {expected_pnl})")

# ── TEST 6: Dashboard full snapshot coherence ─────────────────────────
print("\n=== TEST 6: Dashboard full snapshot coherence ===")
r = requests.get(f"{BASE}/dashboard/", headers=headers)
snap = r.json()
snap_pnl = snap.get("pnl", {}).get("realized_pnl", -999)
snap_funds_avail = snap.get("funds", {}).get("available_cash", -999)
check("dashboard/.pnl.realized_pnl", snap_pnl,
      lambda v: abs(v - expected_pnl) < 0.01,
      f"(expected {expected_pnl})")
check("dashboard/.funds.available_cash", snap_funds_avail,
      lambda v: v > 0,
      "(expected >0)")

# ── SUMMARY ──────────────────────────────────────────────────────────
print("\n" + "="*60)
print("VERIFICATION SUMMARY")
print("="*60)
passed = sum(1 for r in results if r[0] == PASS)
failed = sum(1 for r in results if r[0] == FAIL)
for status, label, got, note in results:
    print(f"  {status}  {label}: {got}  {note}")
print(f"\n  TOTAL: {passed} PASS / {failed} FAIL")
if failed == 0:
    print("\n  ✅ ALL CHECKS PASSED — Backend↔Frontend data is CONSISTENT")
else:
    print(f"\n  ❌ {failed} CHECKS FAILED — see above")
