#!/usr/bin/env python3
"""
Simple Sports Bot - Reliable Version
"""
import os, json, time
from datetime import datetime

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

from pykalshi import KalshiClient

BALANCE = 1500
TARGET = 0.20   # 20% profit target
STOP = 0.10    # 10% stop loss (tighter)
SIZE = 0.12      # 12% per trade (smaller)

client = None
balance = BALANCE
trades = []
positions = []
prices = {}

def main():
    global balance, trades, prices
    
    try:
        with open('sports_state.json', 'r') as f:
            data = json.load(f)
            balance = data.get('balance', BALANCE)
            trades = data.get('trades', [])
    except: pass
    
    print(f"Starting - Balance: ${balance}")
    
    while True:
        try:
            markets = client.get_markets(limit=1000, mve_filter='exclude')
            active = [m for m in markets if m.volume > 0]
            
            # Check exits
            market_dict = {m.ticker: m for m in active}
            for p in list(positions):
                if p['status'] != 'open': continue
                if p['ticker'] not in market_dict: continue
                
                m = market_dict[p['ticker']]
                mid = (m.yes_bid + m.yes_ask) / 200 if m.yes_bid else 0
                
                pct = (mid - p['entry']) / p['entry'] if p['side'] == 'YES' else (p['entry'] - mid) / p['entry']
                
                if pct >= TARGET or pct <= -STOP:
                    pnl = pct * p['contracts']
                    balance += p['contracts'] + pnl
                    p['status'] = 'closed'
                    p['pnl'] = pnl
                    trades.append(p)
                    print(f"{'WIN' if pnl > 0 else 'LOSS'}: ${pnl:.0f}")
            
            # Check entries
            for m in active:
                if any(p['status'] == 'open' and p['ticker'] == m.ticker for p in positions): continue
                
                mid = (m.yes_bid + m.yes_ask) / 200 if m.yes_bid else 0
                if mid == 0: continue
                
                if m.ticker not in prices: prices[m.ticker] = []
                prices[m.ticker].append(mid)
                if len(prices[m.ticker]) < 2: continue
                
                change = mid - prices[m.ticker][0]
                
                # 8% momentum
                if abs(change) >= 0.12:
                    side = 'YES' if change > 0 else 'NO'
                    contracts = int(balance * SIZE)
                    if contracts >= 1:
                        pos = {
                            'ticker': m.ticker, 'title': m.title[:50],
                            'side': side, 'entry': mid,
                            'contracts': contracts, 'status': 'open',
                            'time': datetime.now().isoformat()
                        }
                        positions.append(pos)
                        balance -= contracts
                        print(f"ENTER {side} @ {mid*100:.0f}c {m.title[:30]}...")
            
            # Save
            with open('sports_state.json', 'w') as f:
                json.dump({'balance': balance, 'trades': trades[-20:]}, f, default=str)
            
            time.sleep(5)
            
        except Exception as e:
            print(f"Error: {e}")
            time.sleep(10)

if __name__ == '__main__':
    client = KalshiClient()
    main()
