"""Running P&L for the live maker, decomposed and surviving settlement.

Reading it off open positions does not work: a book that settles drops out of
the position list, so completions keep vanishing from the tally and the total
silently shrinks. This reconstructs every book from the FILL history, which is
permanent, and marks each one either at its settled result or at the current
market.

Splits completions from partials, because they are different animals: a
completed book is locked and outcome-independent, a partial is a directional
bet we did not intend to make.
"""
import collections, sys

sys.path.insert(0, r'E:\soccer\main')
import kalshi_trader as kt
import mm_maker_live as ML

# The session spans a UTC midnight. Filtering on a single date silently
# dropped every fill after 00:00Z -- two completed books read as 2/3 because
# their draw legs landed at 00:47 and 01:11 on the 17th. Use a cutoff instead
# of a calendar day, defaulting to the last 24 hours.
import datetime as _dt
SINCE = (_dt.datetime.now(_dt.timezone.utc)
         - _dt.timedelta(hours=24)).isoformat()


def main():
    fills = collections.defaultdict(lambda: [0.0, 0.0, 0.0])   # qty, cash, fee
    for f in (kt.get_fills().get('fills') or []):
        if str(f.get('created_time', '')) < SINCE:
            continue
        if f.get('is_taker') or str(f.get('side', '')).lower() == 'yes':
            continue
        if str(f.get('action', '')).lower() != 'sell':
            continue
        a = fills[f['ticker']]
        q = float(f.get('count_fp') or 0)
        a[0] += q
        a[1] += float(f.get('yes_price_dollars') or 0) * q
        a[2] += float(f.get('fee_cost') or 0)

    books = collections.defaultdict(list)
    for t in fills:
        books['-'.join(t.split('-')[:2])].append(t)

    pos = {p['ticker']: float(p.get('position_fp') or 0)
           for p in (kt.get_positions().get('market_positions') or [])}

    comp_n = part_n = 0
    comp_pnl = part_pnl = 0.0
    oversold = []
    lines = []
    for ev, ts in sorted(books.items()):
        coll = sum(fills[t][1] for t in ts)
        fee = sum(fills[t][2] for t in ts)
        qty = {t: fills[t][0] for t in ts}
        over = [t for t in ts if qty[t] > 1.0001]
        # settled? every leg gone from positions and we had a position
        settled = all(abs(pos.get(t, 0.0)) < 1e-9 for t in ts)
        name = ev.replace('KX', '')[:30]

        # COMPLETE means every leg sold a FULL contract, not merely that all
        # three legs traded. BARCARC filled 0.32 of BAR and was scored as a
        # finished book at -21.84c, when in truth it is a partial that owes
        # only 0.32 on that outcome. A fractional leg is an unfinished leg.
        full = all(qty[t] >= 0.999 for t in ts)
        if len(ts) == 3 and full and not over:
            comp_n += 1
            p = coll - fee - 1.0
            comp_pnl += p
            lines.append(f'  COMPLETE {name:30} {coll*100:>5.0f}c  '
                         f'{p*100:>+6.2f}c' + ('  (settled)' if settled else ''))
            continue

        if over:
            oversold.append((ev, over))
        # partial (or over-sold): mark each short at what it would cost to close
        mtm = 0.0
        unknown = False
        for t in ts:
            try:
                m = (kt.get_market(t) or {}).get('market', {})
                now = m.get('yes_ask_dollars')
                st = m.get('status')
                res = (m.get('result') or '').strip()
            except Exception:
                unknown = True
                break
            q = qty[t]
            if res in ('yes', 'no'):
                mtm += fills[t][1] - (q if res == 'yes' else 0.0)
            elif now is not None:
                mtm += fills[t][1] - q * float(now)
            else:
                unknown = True
        if unknown:
            continue
        part_n += 1
        part_pnl += mtm - fee
        lines.append(f'  {len(ts)}/3      {name:30} {coll*100:>5.0f}c  '
                     f'{(mtm-fee)*100:>+6.2f}c'
                     + ('  OVER-SOLD' if over else '')
                     + ('  (settled)' if settled else ''))

    print('\n'.join(lines))
    print()
    print(f'  completed books : {comp_n:>3}   {comp_pnl*100:>+8.2f}c')
    print(f'  partial books   : {part_n:>3}   {part_pnl*100:>+8.2f}c')
    print(f'  {"":16}        ----------')
    print(f'  {"session":>16}        {(comp_pnl+part_pnl)*100:>+8.2f}c')
    if oversold:
        print(f'\n  over-sold legs (duplicate fills): '
              f'{", ".join(t.rsplit("-",1)[1] for _, ts in oversold for t in ts)}')
    eq = ML.account_equity()
    if eq is not None:
        print(f'\n  account equity ${eq:.2f}  ({eq-ML.FUNDED_USD:+.2f} vs funded)')


if __name__ == '__main__':
    main()
