"""
BTC 15-Minute Bot - 24/7 Version
Runs continuously, restarts on completion
"""

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

# Config
PAPER_BALANCE = 1500
TARGET = 0.15
STOP = 0.10
POSITION = 0.25
CIRCUIT_BREAKER = 3
CYCLE_DELAY = 2
CYCLES_PER_RUN = 50

def run_bot():
    print(f"\n🚀 BTC 15m Bot Starting at {datetime.now().strftime('%H:%M:%S')}")
    
    client = KalshiClient()
    
    # Load previous balance if exists
    try:
        with open('btc15m_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 = {}
    consecutive_losses = 0
    
    print(f"   Balance: ${balance}")
    
    for cycle in range(CYCLES_PER_RUN):
        try:
            # Get markets
            markets = client.get_markets(series_ticker='KXBTC15M')
            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']]
                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
                    p['exit_time'] = datetime.now().isoformat()
                    trades.append(p)
                    consecutive_losses = 0
                    print(f"  ✅ WIN +${pnl:.0f}")
                    
                elif pnl_pct <= -STOP:
                    pnl = pnl_pct * p['contracts']
                    balance += p['contracts'] + pnl
                    p['status'] = 'closed'
                    p['pnl'] = pnl
                    p['exit_time'] = datetime.now().isoformat()
                    trades.append(p)
                    consecutive_losses += 1
                    print(f"  ❌ LOSS ${pnl:.0f}")
            
            # Check circuit breaker
            if consecutive_losses >= CIRCUIT_BREAKER:
                print(f"  🛑 Circuit breaker triggered")
                time.sleep(60)  # Pause for 1 minute
                consecutive_losses = 0
            
            # Check entries
            for m in active:
                if any(p['status'] == 'open' and p['ticker'] == m.ticker for p in positions):
                    continue
                
                yes_mid = (m.yes_bid + m.yes_ask) / 200 if m.yes_bid or m.yes_ask else 0
                if yes_mid == 0:
                    continue
                
                # Track price
                if m.ticker not in prices:
                    prices[m.ticker] = []
                prices[m.ticker].append(yes_mid)
                
                if len(prices[m.ticker]) < 2:
                    continue
                
                first = prices[m.ticker][0]
                change = yes_mid - first
                
                # Enter on 3%+ momentum
                if abs(change) >= 0.03:
                    side = 'YES' if change > 0 else 'NO'
                    contracts = int(balance * POSITION)
                    
                    if contracts >= 1:
                        pos = {
                            'ticker': m.ticker,
                            'side': side,
                            'entry': yes_mid,
                            'contracts': contracts,
                            'entry_time': datetime.now().isoformat(),
                            'status': 'open'
                        }
                        positions.append(pos)
                        balance -= contracts
                        print(f"  📝 ENTER {side} @ {yes_mid*100:.0f}c | ${contracts}")
            
            # Save state periodically
            if cycle % 10 == 0:
                with open('btc15m_247_state.json', 'w') as f:
                    json.dump({'balance': balance, 'trades': trades[-50:]}, f, default=str)
            
            time.sleep(CYCLE_DELAY)
            
        except Exception as e:
            print(f"  Error: {e}")
            time.sleep(5)
    
    # Final save
    with open('btc15m_247_state.json', 'w') as f:
        json.dump({'balance': balance, 'trades': trades[-50:]}, f, default=str)
    
    print(f"\n   Run complete. Balance: ${balance}")
    
    return balance, trades

# Run continuously
if __name__ == '__main__':
    while True:
        print("\n" + "="*50)
        balance, trades = run_bot()
        print(f"\n💤 Restarting in 5 seconds...")
        time.sleep(5)
