#!/usr/bin/env python3
"""
Smart Bot - Enter on rising price, 30-60c range
"""
import os, json, time
from datetime import datetime, timezone

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, MarketStatus

SERIES = 'KXETH15M'
STATE_FILE = 'eth_state.json'
HIST_FILE = 'eth_history.json'

SIZE = 0.03  # 3%
MIN_PROFIT = 0.01  # 1%

# Price tracking
prices = {}

def main():
    try:
        with open(HIST_FILE) as f:
            history = json.load(f)
    except:
        history = []
    
    pnl = sum(t.get('pnl', 0) for t in history)
    balance = 1500 + pnl
    
    position = None
    last_ticker = None
    
    print(f"Starting - Balance: ${balance}")
    
    client = KalshiClient()
    
    while True:
        try:
            markets = client.get_markets(series_ticker=SERIES, status=MarketStatus.OPEN, limit=3)
            if not markets:
                time.sleep(5)
                continue
            
            m = markets[0]
            mid = m.yes_ask / 100 if m.yes_ask else 0
            now = datetime.now(timezone.utc)
            close = datetime.fromisoformat(m.close_time.replace('Z', '+00:00'))
            left = int((close - now).total_seconds())
            
            # Track price
            if m.ticker not in prices:
                prices[m.ticker] = []
            prices[m.ticker].append({'time': now, 'price': mid})
            
            # Keep only last 3 readings
            if len(prices[m.ticker]) > 3:
                prices[m.ticker] = prices[m.ticker][-3:]
            
            # Calculate momentum
            momentum = 0
            if len(prices[m.ticker]) >= 2:
                first = prices[m.ticker][0]['price']
                if first > 0:
                    momentum = (mid - first) / first
            
            # New market - reset
            if last_ticker and m.ticker != last_ticker:
                last_ticker = None
            
            # Exit: if we have position
            if position and position['ticker'] == m.ticker:
                pct = (mid - position['entry']) / position['entry']
                
                # Exit at 4 min left if profit OR at 1 min left regardless
                if (left <= 240 and pct > MIN_PROFIT) or left <= 60:
                    pnl = (mid - position['entry']) * position['contracts']
                    balance += position['cost'] + pnl
                    position['exit'] = mid
                    position['pnl'] = pnl
                    history.append(position)
                    with open(HIST_FILE, 'w') as f:
                        json.dump(history, f, default=str)
                    print(f"EXIT: {'WIN' if pnl > 0 else 'LOSS'} ${pnl:.0f} | Balance: ${balance:.0f}")
                    position = None
                    last_ticker = m.ticker
            
            # ENTER: New smart rules
            # 1. 300-480 seconds left (5-8 min before close)
            # 2. Price 30-60c (sweet spot)
            # 3. Rising momentum (positive change)
            if (not position and m.ticker != last_ticker and 
                180 < left <= 480 and 
                0.20 <= mid <= 0.80 and  # 30-65c range
                momentum > 0.01):  # Rising
                
                contracts = int(balance * SIZE / mid)
                if contracts >= 1:
                    cost = contracts * mid
                    balance -= cost
                    position = {
                        'ticker': m.ticker,
                        'entry': mid,
                        'contracts': contracts,
                        'cost': cost,
                        'time': datetime.now().isoformat()
                    }
                    last_ticker = m.ticker
                    print(f"ENTER {m.ticker} @ {mid*100:.0f}c ${cost:.0f} | {left}s left | Momentum: {momentum*100:.0f}%")
            
            with open(STATE_FILE, 'w') as f:
                json.dump({'balance': balance, 'trades': [position] if position else []}, f, default=str)
            
            time.sleep(2)
        except Exception as e:
            print(f"Error: {e}")
            time.sleep(5)

if __name__ == '__main__':
    main()
