"""
BTC 15-Minute Bot - Aggressive Last-2-Minutes
"""

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.10  # Lower target - 10%
STOP = 0.05    # Tighter stop - 5%
POSITION = 0.30  # Bigger position - 30%

print("🚀 BTC 15m Aggressive Bot")
print(f"   ${PAPER_BALANCE} | Target: +{TARGET*100:.0f}% | Stop: -{STOP*100:.0f}%")
print()

client = KalshiClient()
balance = PAPER_BALANCE
positions = []
trades = []
prices = {}

for cycle in range(100):
    try:
        markets = client.get_markets(series_ticker='KXBTC15M')
        active = [m for m in markets if m.volume > 0]
        
        # Get current time
        now = datetime.now()
        current_minute = now.minute
        current_second = now.second
        seconds_remaining = 60 - current_second + (14 - (current_minute % 15)) * 60
        
        # Show status
        open_pos = len([p for p in positions if p['status'] == 'open'])
        if open_pos > 0 or len(active) > 0:
            print(f"[{cycle+1}] Active: {len(active)} | Open: {open_pos} | Balance: ${balance:.0f} | {seconds_remaining}s left")
        
        # 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
                trades.append(p)
                print(f"  ✅ WIN +${pnl:.0f} ({pnl_pct*100:.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 - MORE AGGRESSIVE in last 2 minutes
        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
            
            # Parse time from ticker to get time remaining
            try:
                parts = m.ticker.split('-')
                time_str = parts[2] + parts[3]  # e.g., 191915
                exp_min = int(time_str[4:6])
                exp_sec = int(time_str[6:8])
                
                # Calculate seconds until this market expires
                # Markets are at :00, :15, :30, :45
                market_expire_second = exp_min * 60 + exp_sec
                current_second_total = now.minute * 60 + now.second
                time_left = market_expire_second - current_second_total
                
            except:
                time_left = 999  # Unknown
            
            # 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 in last 2 minutes (120 seconds) with even smaller momentum
            if time_left <= 120 and time_left > 0:
                # Even 1.5%+ move is enough in last 2 minutes
                if change >= 0.015:  # 1.5%+
                    side = 'YES'
                    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',
                            'time_left': time_left
                        }
                        positions.append(pos)
                        balance -= contracts
                        print(f"  📝 LATE ENTRY {side} @ {yes_mid*100:.1f}c | ${contracts} | {time_left}s left")
                        
                elif change <= -0.015:  # 1.5%+ down
                    side = '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',
                            'time_left': time_left
                        }
                        positions.append(pos)
                        balance -= contracts
                        print(f"  📝 LATE ENTRY {side} @ {yes_mid*100:.1f}c | ${contracts} | {time_left}s left")
        
        # Save state
        if cycle % 5 == 0:
            with open('btc15m_247_state.json', 'w') as f:
                json.dump({'balance': balance, 'trades': trades}, f, default=str)
        
        time.sleep(1)  # Check every second in last 2 minutes
        
    except Exception as e:
        print(f"Error: {e}")
        time.sleep(2)

# 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} | Win Rate: {wins/len(closed)*100:.0f}%")

with open('btc15m_247_state.json', 'w') as f:
    json.dump({'balance': balance, 'trades': trades}, f, default=str)
print("💾 Saved")
