"""
Sports Bot - 24/7 Version
Runs continuously, catches games whenever they appear
"""

import os
import json
import time
from datetime import datetime

os.environ['KALSHI_API_KEY_ID'] = '81fe00fc-27b2-48ca-85f8-9c37ec1dc82f'
os.environ['KALSHI_PRIVATE_KEY_PATH'] = './kalshi_private_key'

from pykalshi import KalshiClient

PAPER_BALANCE = 1500
TARGET = 0.15
STOP = 0.12
POSITION = 0.10
MAX_OPEN = 3
REV_THRESHOLD = 0.06

print("🏀 Sports Bot 24/7")
print(f"   ${PAPER_BALANCE} | Target: +{TARGET*100:.0f}% | Stop: -{STOP*100:.0f}%")
print()

client = KalshiClient()

# Load state
try:
    with open('sports_247_state.json', 'r') as f:
        state = json.load(f)
        balance = state.get('balance', PAPER_BALANCE)
        trades = state.get('trades', [])
except:
    balance = PAPER_BALANCE
    trades = []

positions = []
prices = {}

for cycle in range(200):
    try:
        # Get sports markets
        markets = client.get_markets(status='open', limit=500)
        
        # Filter for spreads/totals in ATSwins leagues
        leagues = ['nfl','nba','nhl','mlb','ncaab','ncaaf','college basketball','college football']
        sports = []
        for m in markets:
            if m.volume > 0:
                title = m.title.lower()
                if ('wins by' in title or 'over ' in title or 'under ' in title) and any(lg in title for lg in leagues):
                    sports.append(m)
        
        # Show status
        open_pos = len([p for p in positions if p['status'] == 'open'])
        
        if open_pos > 0 or len(sports) > 0:
            print(f"[{cycle+1}] Markets: {len(sports)} | Open: {open_pos} | Balance: ${balance:.0f}")
        
        # Check exits
        market_dict = {m.ticker: m for m in sports}
        
        for p in list(positions):
            if p['status'] != 'open':
                continue
            if p['ticker'] not in market_dict:
                continue
            
            m = market_dict[p['ticker']]
            yes_mid = (m.yes_bid + m.yes_ask) / 200 if m.yes_bid or m.yes_ask else 0
            
            if p['side'] == 'YES':
                pnl_pct = (yes_mid - p['entry']) / p['entry'] if p['entry'] > 0 else 0
            else:
                pnl_pct = (p['entry'] - yes_mid) / p['entry'] if p['entry'] > 0 else 0
            
            if pnl_pct >= TARGET:
                pnl = pnl_pct * p['contracts']
                balance += p['contracts'] + pnl
                p['status'] = 'closed'
                p['pnl'] = pnl
                trades.append(p)
                print(f"  ✅ WIN +${pnl:.0f}")
                
            elif pnl_pct <= -STOP:
                pnl = pnl_pct * p['contracts']
                balance += p['contracts'] + pnl
                p['status'] = 'closed'
                p['pnl'] = pnl
                trades.append(p)
                print(f"  ❌ LOSS ${pnl:.0f}")
        
        # Check entries - mean reversion fade
        open_pos = len([p for p in positions if p['status'] == 'open'])
        for m in sports:
            if any(p['status'] == 'open' and p['ticker'] == m.ticker for p in positions):
                continue
            if open_pos >= MAX_OPEN:
                break

            yes_mid = (m.yes_bid + m.yes_ask) / 200 if m.yes_bid or m.yes_ask else 0
            if yes_mid == 0:
                continue

            if m.ticker not in prices:
                prices[m.ticker] = []
            prices[m.ticker].append(yes_mid)
            if len(prices[m.ticker]) > 6:
                prices[m.ticker] = prices[m.ticker][-6:]

            if len(prices[m.ticker]) < 4:
                continue

            avg = sum(prices[m.ticker]) / len(prices[m.ticker])
            diff = yes_mid - avg

            if diff >= REV_THRESHOLD:
                side = 'NO'
            elif diff <= -REV_THRESHOLD:
                side = 'YES'
            else:
                continue

            contracts = int(balance * POSITION)
            if contracts >= 1:
                pos = {
                    'ticker': m.ticker,
                    'title': m.title[:50],
                    'side': side,
                    'entry': yes_mid,
                    'contracts': contracts,
                    'entry_time': datetime.now().isoformat(),
                    'status': 'open'
                }
                positions.append(pos)
                balance -= contracts
                open_pos += 1
                print(f"  📝 ENTER {side} @ {yes_mid*100:.0f}c | {m.title[:30]}...")
        
        # Save
        if cycle % 10 == 0:
            with open('sports_247_state.json', 'w') as f:
                json.dump({'balance': balance, 'trades': trades[-50:]}, f, default=str)
        
        time.sleep(5)
        
    except Exception as e:
        print(f"Error: {e}")
        time.sleep(10)

# Final
print("\n" + "="*50)
print(f"FINAL: ${balance:.2f}")

closed = [t for t in trades if t['status'] == 'closed']
if closed:
    wins = len([t for t in closed if t.get('pnl', 0) > 0])
    print(f"Trades: {len(closed)} | Wins: {wins}")

with open('sports_247_state.json', 'w') as f:
    json.dump({'balance': balance, 'trades': trades}, f, default=str)
