"""Live check: current open Kalshi positions, paper P&L marked to bid."""
import kalshi_trader as kt
from collections import defaultdict
from datetime import datetime

# Pull all fills
all_fills = []
cursor = None
while True:
    params = {"limit": 200}
    if cursor:
        params["cursor"] = cursor
    resp = kt._get("/portfolio/fills", params=params)
    fills = resp.get("fills", [])
    if not fills:
        break
    all_fills.extend(fills)
    cursor = resp.get("cursor")
    if not cursor:
        break

# Group fills by ticker and compute net position
by_ticker = defaultdict(list)
for f in all_fills:
    by_ticker[f["ticker"]].append(f)

# Iterate open positions
pos = kt.get_positions()
mkts = pos.get("market_positions", [])
open_mkts = [p for p in mkts if float(p.get("position_fp", 0)) > 0]

print(f"Open positions: {len(open_mkts)}")
print()
print(f"{'MATCH':<50} {'QTY':>7} {'AVG':>6} {'BID':>6} {'P/L':>8}  STATUS")
print("-" * 95)

total_pnl = 0.0
total_cost = 0.0

for p in open_mkts:
    t = p["ticker"]
    qty = float(p["position_fp"])
    cost = float(p["market_exposure_dollars"])
    avg_px = cost / qty if qty else 0
    total_cost += cost

    try:
        m = kt.get_market(t).get("market", {})
        status = m.get("status", "?")
        bid_s = m.get("yes_bid_dollars")
        last_s = m.get("last_price_dollars")
        bid = float(bid_s) if bid_s else 0.0
        last = float(last_s) if last_s else 0.0
    except Exception as e:
        status, bid, last = "err", 0.0, 0.0

    pnl = (bid - avg_px) * qty
    total_pnl += pnl

    # Pretty match name
    parts = t.split("-")
    date_teams = parts[1] if len(parts) > 1 else ""
    side = parts[2] if len(parts) > 2 else ""
    short = f"{date_teams[7:]} -> {side}"

    print(f"{short:<50} {qty:>7.1f} ${avg_px:>5.2f} ${bid:>5.2f} ${pnl:>+7.2f}  {status}")

print("-" * 95)
print(f"{'TOTAL COST':<50} {'':>7} {'':>6} {'':>6} ${total_cost:>+7.2f}")
print(f"{'PAPER P&L (mark to bid)':<50} {'':>7} {'':>6} {'':>6} ${total_pnl:>+7.2f}")
print()

# Also show RECENT settled (today's resolved)
print("Recently settled (status != active):")
print("-" * 95)
# Look at all unique tickers from recent fills
recent_tickers = set()
cutoff = datetime.now().timestamp() - 36 * 3600  # last 36h
for f in all_fills:
    if f["ts"] > cutoff:
        recent_tickers.add(f["ticker"])

settled_pnl = 0.0
for t in recent_tickers:
    # Skip if currently open
    if any(p["ticker"] == t and float(p.get("position_fp", 0)) > 0 for p in mkts):
        continue
    fls = by_ticker[t]
    yes = [f for f in fls if f["side"] == "yes"]
    no_ = [f for f in fls if f["side"] == "no"]
    yes_qty = sum(float(f["count_fp"]) for f in yes)
    no_qty = sum(float(f["count_fp"]) for f in no_)
    if abs(yes_qty - no_qty) > 0.01:
        # Net long → settled by expiration
        try:
            m = kt.get_market(t).get("market", {})
            result = m.get("result", "")
            status = m.get("status", "")
        except Exception:
            result, status = "?", "?"
        cost = sum(float(f["count_fp"]) * float(f["yes_price_dollars"]) for f in yes) - \
               sum(float(f["count_fp"]) * float(f["no_price_dollars"]) for f in no_)
        net_qty = yes_qty - no_qty
        # Settlement: if result is 'yes', net_qty * $1, else 0
        if result == "yes":
            settle = net_qty * 1.0
        else:
            settle = 0.0
        pnl = settle - cost
        settled_pnl += pnl
        parts = t.split("-")
        short = f"{parts[1][7:]} -> {parts[2] if len(parts)>2 else ''}"
        print(f"{short:<50} qty={net_qty:>5.1f}  cost=${cost:>+5.2f}  settle=${settle:>+5.2f}  P/L=${pnl:>+6.2f}  [{result or status}]")

print("-" * 95)
print(f"Today's settled P&L: ${settled_pnl:+.2f}")
