"""
market_proxy.py — runs on VPS alongside whale_bot.py
Fetches all external market data server-side (no CORS issues)
Exposes /api/market, /api/btc_chart, /api/ohlc, /api/portfolio endpoints
Run with: pm2 start market_proxy.py --interpreter python3 --name market-proxy
"""
import json
import os
import requests
import threading
from datetime import datetime, timedelta
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn

PORT = 8081
PORTFOLIO_FILE = '/root/whale-bot/portfolio_history.json'

cache = {
    'prices':     {'data': None, 'ts': 0},
    'sparklines': {'data': None, 'ts': 0},
    'metals':     {'data': None, 'ts': 0},
    'macro':      {'data': None, 'ts': 0},
    'fg':         {'data': None, 'ts': 0},
    'news':       {'data': None, 'ts': 0},
    'global':     {'data': None, 'ts': 0},
    'mvrv':       {'data': None, 'ts': 0},
    'stablecoins': {'data': None, 'ts': 0},
    'derivatives': {'data': None, 'ts': 0},
    'btc_chart':  {},
    'ohlc':       {},
}

HEADERS = {'User-Agent': 'Mozilla/5.0 (compatible; CryptoDashboard/1.0)'}

# OHLC asset mapping. CoinGecko-backed assets use the coins/{id}/ohlc endpoint;
# Yahoo-backed assets (SPY via ^GSPC, gold optional fallback) use the chart API.
OHLC_ASSETS = {
    'btc':  {'source': 'coingecko', 'id': 'bitcoin'},
    'sol':  {'source': 'coingecko', 'id': 'solana'},
    'gold': {'source': 'coingecko', 'id': 'pax-gold'},
    'spy':  {'source': 'yahoo',     'symbol': '^GSPC'},
    'nvda': {'source': 'yahoo',     'symbol': 'NVDA'},
    'vix':  {'source': 'yahoo',     'symbol': '^VIX'},
}

# Live portfolio quantities — must mirror QTY in dashboard.html for the AI briefing.
PORTFOLIO_QTY = {
    'cold_btc':   0.3494,
    'cdc_hype':   3.773,
    'cdc_sol':    5.5444,
    'cdc_cro':    4064.46,
    'cdc_jup':    678.54,
    'cdc_akt':    172.45,
    'cdc_inj':    29.3635,
    'cdc_render': 50.363,
    'cdc_sui':    149.44,
}

# ─── PORTFOLIO HISTORY ────────────────────────────────────────
def load_portfolio_history():
    try:
        if os.path.exists(PORTFOLIO_FILE):
            with open(PORTFOLIO_FILE, 'r') as f:
                return json.load(f)
    except:
        pass
    return []

def save_portfolio_snapshot(total_usd):
    """Append a snapshot. One per hour max to keep file small."""
    history = load_portfolio_history()
    now = datetime.utcnow()
    # Only save if last snapshot is >50 minutes ago
    if history:
        last_ts = datetime.fromisoformat(history[-1]['timestamp'])
        if (now - last_ts).total_seconds() < 3000:
            return
    history.append({
        'timestamp': now.isoformat(),
        'total_usd': round(total_usd, 2),
    })
    # Keep last 400 entries (~16 days of hourly snapshots)
    history = history[-400:]
    try:
        with open(PORTFOLIO_FILE, 'w') as f:
            json.dump(history, f)
    except Exception as e:
        print(f'Portfolio save error: {e}')

# ─── DATA FETCHERS ────────────────────────────────────────────
def fetch_prices():
    if (datetime.now().timestamp() - cache['prices']['ts']) < 30:
        return cache['prices']['data']
    try:
        ids = 'bitcoin,ethereum,solana,crypto-com-chain,jupiter-exchange-solana,akash-network,injective-protocol,fetch-ai,render-token,sui,internet-computer,hyperliquid'
        r = requests.get(
            f'https://api.coingecko.com/api/v3/simple/price?ids={ids}&vs_currencies=usd&include_24hr_change=true',
            timeout=10, headers=HEADERS
        )
        data = r.json()
        cache['prices'] = {'data': data, 'ts': datetime.now().timestamp()}
        return data
    except Exception as e:
        print(f'Price fetch error: {e}')
        return cache['prices']['data']

def fetch_sparklines():
    if (datetime.now().timestamp() - cache['sparklines']['ts']) < 300:
        return cache['sparklines']['data']
    try:
        # Include paxg (PAX Gold) for gold sparkline proxy
        r = requests.get(
            'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=bitcoin,solana,pax-gold&sparkline=true',
            timeout=10, headers=HEADERS
        )
        data = r.json()
        cache['sparklines'] = {'data': data, 'ts': datetime.now().timestamp()}
        return data
    except Exception as e:
        print(f'Sparkline fetch error: {e}')
        return cache['sparklines']['data']

def fetch_metals():
    if (datetime.now().timestamp() - cache['metals']['ts']) < 300:
        return cache['metals']['data']
    try:
        gold   = requests.get('https://api.gold-api.com/price/XAU', timeout=10, headers=HEADERS).json()
        silver = requests.get('https://api.gold-api.com/price/XAG', timeout=10, headers=HEADERS).json()
        data = {'gold': gold, 'silver': silver}
        cache['metals'] = {'data': data, 'ts': datetime.now().timestamp()}
        return data
    except Exception as e:
        print(f'Metals fetch error: {e}')
        return cache['metals']['data']

def compute_returns(closes):
    """Compute 1D/5D/20D percentage returns from a closes array (oldest->newest).
    Returns None for windows where there isn't enough history yet."""
    returns = {}
    returns['r1d']  = round((closes[-1] - closes[-2]) / closes[-2] * 100, 2) if len(closes) >= 2 else None
    returns['r5d']  = round((closes[-1] - closes[-6]) / closes[-6] * 100, 2) if len(closes) >= 6 else None
    returns['r20d'] = round((closes[-1] - closes[-21]) / closes[-21] * 100, 2) if len(closes) >= 21 else None
    return returns

def fetch_macro():
    if (datetime.now().timestamp() - cache['macro']['ts']) < 300:
        return cache['macro']['data']
    results = {}
    symbols = {
        'oil': 'CL=F', 'sp500': '^GSPC', 'dxy': 'DX-Y.NYB',
        'qqq': 'QQQ', 'soxx': 'SOXX', 'us10y': '^TNX',
        'nvda': 'NVDA', 'vix': '^VIX',
    }
    yf_headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'Accept': 'application/json',
        'Referer': 'https://finance.yahoo.com',
    }
    for key, sym in symbols.items():
        try:
            r = requests.get(
                f'https://query1.finance.yahoo.com/v8/finance/chart/{requests.utils.quote(sym)}?interval=1d&range=1mo',
                timeout=10, headers=yf_headers
            )
            d = r.json()
            result = d.get('chart', {}).get('result', [{}])[0]
            closes = [c for c in (result.get('indicators', {}).get('quote', [{}])[0].get('close', [])) if c is not None]
            if closes:
                results[key] = {
                    'closes':  closes,
                    'current': closes[-1],
                    'prev':    closes[-2] if len(closes) > 1 else closes[-1],
                    **compute_returns(closes),
                }
        except Exception as e:
            print(f'Yahoo error for {sym}: {e}')
    cache['macro'] = {'data': results, 'ts': datetime.now().timestamp()}
    return results

def fetch_global():
    if (datetime.now().timestamp() - cache['global']['ts']) < 300:
        return cache['global']['data']
    try:
        r = requests.get('https://api.coingecko.com/api/v3/global', timeout=10, headers=HEADERS)
        data = r.json()
        cache['global'] = {'data': data, 'ts': datetime.now().timestamp()}
        return data
    except Exception as e:
        print(f'Global fetch error: {e}')
        return cache['global']['data']

def fetch_etf_flows():
    """ETF flow scraping disabled — return nulls so the dashboard can show
    'unavailable' gracefully without attempting any external request."""
    return {
        'btc_etf_flow_1d': None,
        'btc_etf_flow_7d': None,
        'eth_etf_flow_1d': None,
        'eth_etf_flow_7d': None,
        'status': 'unavailable',
    }

def fetch_stablecoins():
    if (datetime.now().timestamp() - cache['stablecoins']['ts']) < 14400:
        return cache['stablecoins']['data']
    try:
        r = requests.get(
            'https://api.coingecko.com/api/v3/simple/price?ids=tether,usd-coin&vs_currencies=usd&include_market_cap=true',
            timeout=10, headers=HEADERS
        )
        data = r.json()
        result = {
            'usdt_mcap': data.get('tether', {}).get('usd_market_cap'),
            'usdc_mcap': data.get('usd-coin', {}).get('usd_market_cap'),
        }
        cache['stablecoins'] = {'data': result, 'ts': datetime.now().timestamp()}
        return result
    except Exception as e:
        print(f'Stablecoin fetch error: {e}')
        return cache['stablecoins']['data']

def fetch_derivatives():
    if (datetime.now().timestamp() - cache['derivatives']['ts']) < 600:
        return cache['derivatives']['data']
    api_key = os.environ.get('COINGLASS_API_KEY', '').strip()
    if not api_key:
        result = {
            'btc_funding_rate':  None,
            'btc_open_interest': None,
            'status': 'needs_api_key',
        }
        cache['derivatives'] = {'data': result, 'ts': datetime.now().timestamp()}
        return result
    # Placeholder — wire up Coinglass endpoints once a key is configured
    result = {'btc_funding_rate': None, 'btc_open_interest': None, 'status': 'not_implemented'}
    cache['derivatives'] = {'data': result, 'ts': datetime.now().timestamp()}
    return result

def fetch_mvrv():
    if (datetime.now().timestamp() - cache['mvrv']['ts']) < 3600:
        return cache['mvrv']['data']
    try:
        r = requests.get(
            'https://community-api.coinmetrics.io/v4/timeseries/asset-metrics'
            '?assets=btc&metrics=CapMVRVCur&frequency=1d&page_size=2',
            timeout=10, headers=HEADERS
        )
        d = r.json()
        series = d.get('data', [])
        mvrv = float(series[-1]['CapMVRVCur']) if series and series[-1].get('CapMVRVCur') else None
        cache['mvrv'] = {'data': mvrv, 'ts': datetime.now().timestamp()}
        return mvrv
    except Exception as e:
        print(f'MVRV fetch error: {e}')
        return cache['mvrv']['data']

def fetch_fear_greed():
    if (datetime.now().timestamp() - cache['fg']['ts']) < 3600:
        return cache['fg']['data']
    try:
        r = requests.get('https://api.alternative.me/fng/?limit=1', timeout=10, headers=HEADERS)
        data = r.json()
        cache['fg'] = {'data': data, 'ts': datetime.now().timestamp()}
        return data
    except Exception as e:
        print(f'Fear & greed error: {e}')
        return cache['fg']['data']

def parse_rss_direct(url, source, limit=4):
    """Fetch and parse an RSS/Atom feed directly without rss2json."""
    import xml.etree.ElementTree as ET
    r = requests.get(url, timeout=8, headers=HEADERS)
    root = ET.fromstring(r.text)
    ns = {'atom': 'http://www.w3.org/2005/Atom'}
    items = []
    # RSS 2.0
    for item in root.findall('.//item')[:limit]:
        title = item.findtext('title', '').strip()
        link  = item.findtext('link', '').strip()
        pub   = item.findtext('pubDate', '')
        if title and link:
            items.append({'title': title, 'url': link, 'source': source, 'published': pub})
    # Atom
    if not items:
        for entry in root.findall('atom:entry', ns)[:limit]:
            title = entry.findtext('atom:title', '', ns).strip()
            link_el = entry.find('atom:link', ns)
            link = link_el.get('href', '') if link_el is not None else ''
            pub  = entry.findtext('atom:published', '', ns)
            if title and link:
                items.append({'title': title, 'url': link, 'source': source, 'published': pub})
    return items

def fetch_news():
    if (datetime.now().timestamp() - cache['news']['ts']) < 120:
        return cache['news']['data']
    items = []
    # Direct RSS feeds — no rss2json dependency
    direct_feeds = [
        ('https://www.coindesk.com/arc/outboundfeeds/rss/', 'CoinDesk'),
        ('https://cointelegraph.com/rss', 'CoinTelegraph'),
        ('https://www.cnbc.com/id/100003114/device/rss/rss.html', 'CNBC'),
        ('https://feeds.content.dowjones.io/public/rss/mw_realtimeheadlines', 'MarketWatch'),
    ]
    for url, source in direct_feeds:
        try:
            new_items = parse_rss_direct(url, source, limit=3)
            items.extend(new_items)
            if len(items) >= 9:
                break
        except Exception as e:
            print(f'Direct RSS error for {source}: {e}')
    cache['news'] = {'data': items, 'ts': datetime.now().timestamp()}
    return items

def fetch_btc_chart(days):
    cache_key = str(days)
    if cache_key in cache['btc_chart']:
        entry = cache['btc_chart'][cache_key]
        ttl = 60 if days == '1' else 300
        if (datetime.now().timestamp() - entry['ts']) < ttl:
            return entry['data']
    # CoinGecko free tier does not support days=max; cap at 365
    fetch_days = '365' if days == 'max' else days
    try:
        url = f'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days={fetch_days}'
        r = requests.get(url, timeout=15, headers=HEADERS)
        data = r.json()
        if not data.get('prices'):
            print(f'BTC chart empty for days={fetch_days}: {list(data.keys())}')
            return cache['btc_chart'].get(cache_key, {}).get('data')
        # Trim 7-day data to exactly 168 hourly points
        if days == '7':
            data['prices'] = data['prices'][-168:]
            if 'market_caps' in data: data['market_caps'] = data['market_caps'][-168:]
            if 'total_volumes' in data: data['total_volumes'] = data['total_volumes'][-168:]
        cache['btc_chart'][cache_key] = {'data': data, 'ts': datetime.now().timestamp()}
        return data
    except Exception as e:
        print(f'BTC chart error for days={days}: {e}')
        return cache['btc_chart'].get(cache_key, {}).get('data')

# ─── OHLC (candlestick) ───────────────────────────────────────
def _yahoo_range_interval(days):
    """Map a days window to Yahoo range+interval producing a sensible candle count."""
    if days == '1':   return '1d',  '5m'
    if days == '7':   return '5d',  '60m'
    if days == '30':  return '1mo', '1d'
    if days == '365': return '1y',  '1d'
    return '1mo', '1d'

def fetch_ohlc_yahoo(symbol, days):
    """Return list of [ts_ms, o, h, l, c] from Yahoo Finance chart API."""
    rng, interval = _yahoo_range_interval(days)
    yf_headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'Accept': 'application/json',
        'Referer': 'https://finance.yahoo.com',
    }
    url = (f'https://query1.finance.yahoo.com/v8/finance/chart/'
           f'{requests.utils.quote(symbol)}?interval={interval}&range={rng}')
    r = requests.get(url, timeout=12, headers=yf_headers)
    d = r.json()
    result = d.get('chart', {}).get('result', [{}])[0]
    ts = result.get('timestamp', []) or []
    q = result.get('indicators', {}).get('quote', [{}])[0]
    opens, highs, lows, closes = (q.get('open', []), q.get('high', []),
                                  q.get('low', []), q.get('close', []))
    candles = []
    for i in range(len(ts)):
        o, h, l, c = (opens[i] if i < len(opens) else None,
                      highs[i] if i < len(highs) else None,
                      lows[i] if i < len(lows) else None,
                      closes[i] if i < len(closes) else None)
        if None in (o, h, l, c):
            continue
        candles.append([ts[i] * 1000, o, h, l, c])
    return candles

def fetch_ohlc_coingecko(coin_id, days):
    """Return list of [ts_ms, o, h, l, c] from CoinGecko OHLC endpoint.
    CoinGecko free tier supports days = 1,7,14,30,90,180,365."""
    fetch_days = '365' if days == 'max' else days
    url = (f'https://api.coingecko.com/api/v3/coins/{coin_id}/ohlc'
           f'?vs_currency=usd&days={fetch_days}')
    r = requests.get(url, timeout=15, headers=HEADERS)
    data = r.json()
    # CoinGecko returns [[ts_ms, o, h, l, c], ...] already
    if not isinstance(data, list):
        return []
    return data

def fetch_ohlc(asset, days):
    """Unified OHLC fetch with per-asset/per-window caching."""
    asset = asset.lower()
    cfg = OHLC_ASSETS.get(asset)
    if not cfg:
        return []
    cache_key = f'{asset}:{days}'
    entry = cache['ohlc'].get(cache_key)
    ttl = 60 if days == '1' else 300
    if entry and (datetime.now().timestamp() - entry['ts']) < ttl:
        return entry['data']
    try:
        if cfg['source'] == 'coingecko':
            candles = fetch_ohlc_coingecko(cfg['id'], days)
        else:
            candles = fetch_ohlc_yahoo(cfg['symbol'], days)
        if candles:
            cache['ohlc'][cache_key] = {'data': candles, 'ts': datetime.now().timestamp()}
            return candles
        # fall back to stale cache if fetch returned nothing
        return entry['data'] if entry else []
    except Exception as e:
        print(f'OHLC fetch error for {asset} days={days}: {e}')
        return entry['data'] if entry else []

def get_btc_price_summary():
    """Extract 7d and 30d BTC price context from cache — no extra API calls."""
    summary = {}
    for label, key in [('d7', '7'), ('d30', '30')]:
        entry = cache['btc_chart'].get(key)
        if entry and entry.get('data') and entry['data'].get('prices'):
            pts = [p[1] for p in entry['data']['prices']]
            if len(pts) >= 2:
                summary[label] = {
                    'open': round(pts[0]),
                    'high': round(max(pts)),
                    'low':  round(min(pts)),
                    'pct':  round((pts[-1] - pts[0]) / pts[0] * 100, 1),
                }
    return summary

def build_briefing_context():
    """Assemble a snapshot of all live cached data for the AI briefing prompt."""
    prices = fetch_prices() or {}
    def price(coin_id):
        return (prices.get(coin_id) or {}).get('usd')
    def chg24h(coin_id):
        return (prices.get(coin_id) or {}).get('usd_24h_change')

    btc = price('bitcoin') or 0
    eth = price('ethereum') or 0
    sol = price('solana') or 0

    mvrv = cache['mvrv']['data']
    fg = fetch_fear_greed() or {}
    fg_entry = (fg.get('data') or [{}])[0]
    fg_val   = fg_entry.get('value')
    fg_label = fg_entry.get('value_classification')

    btc_history = get_btc_price_summary()
    pct30 = btc_history.get('d30', {}).get('pct')

    global_data = fetch_global() or {}
    btc_dom = global_data.get('data', {}).get('market_cap_percentage', {}).get('btc')

    macro       = fetch_macro() or {}
    stablecoins = fetch_stablecoins() or {}
    derivatives = fetch_derivatives() or {}

    eth_btc = (eth / btc) if btc else None
    sol_btc = (sol / btc) if btc else None

    # Portfolio breakdown — keys must mirror QTY in dashboard.html
    asset_map = {
        'cold_btc':   ('BTC',    'bitcoin'),
        'cdc_hype':   ('HYPE',   'hyperliquid'),
        'cdc_sol':    ('SOL',    'solana'),
        'cdc_cro':    ('CRO',    'crypto-com-chain'),
        'cdc_jup':    ('JUP',    'jupiter-exchange-solana'),
        'cdc_akt':    ('AKT',    'akash-network'),
        'cdc_inj':    ('INJ',    'injective-protocol'),
        'cdc_render': ('RENDER', 'render-token'),
        'cdc_sui':    ('SUI',    'sui'),
    }
    portfolio = []
    total = 0
    for key, (name, coin_id) in asset_map.items():
        qty = PORTFOLIO_QTY.get(key, 0)
        px  = price(coin_id) or 0
        val = qty * px
        total += val
        portfolio.append({'name': name, 'qty': qty, 'price': px, 'value': val, 'chg24h': chg24h(coin_id)})
    for a in portfolio:
        a['pct'] = (a['value'] / total * 100) if total else 0

    return {
        'btc': btc, 'eth': eth, 'sol': sol,
        'eth_btc': eth_btc, 'sol_btc': sol_btc,
        'mvrv': mvrv, 'fg_val': fg_val, 'fg_label': fg_label,
        'pct30': pct30, 'btc_history': btc_history,
        'btc_dom': btc_dom,
        'macro': macro, 'stablecoins': stablecoins, 'derivatives': derivatives,
        'portfolio': portfolio, 'portfolio_total': total,
    }

def build_briefing_prompts():
    """Build system/user prompts for the AI briefing from live server-side data."""
    ctx   = build_briefing_context()
    macro = ctx['macro']

    def macro_line(key, label):
        m = macro.get(key)
        if not m or m.get('r1d') is None:
            return f'{label}: unavailable'
        return f"{label}: {m['current']:.2f} ({m['r1d']:+.2f}% 1d)"

    mvrv_str    = f"{ctx['mvrv']:.2f}" if ctx['mvrv'] is not None else 'unavailable'
    fg_str      = f"{ctx['fg_val']} ({ctx['fg_label']})" if ctx['fg_val'] is not None else 'unavailable'
    pct30_str   = f"{ctx['pct30']:+.1f}%" if ctx['pct30'] is not None else 'unavailable'
    dom_str     = f"{ctx['btc_dom']:.1f}%" if ctx['btc_dom'] is not None else 'unavailable'
    eth_btc_str = f"{ctx['eth_btc']:.5f}" if ctx['eth_btc'] is not None else 'unavailable'
    sol_btc_str = f"{ctx['sol_btc']:.6f}" if ctx['sol_btc'] is not None else 'unavailable'

    usdt = ctx['stablecoins'].get('usdt_mcap')
    usdc = ctx['stablecoins'].get('usdc_mcap')
    stable_str = (f"USDT ${usdt/1e9:.1f}B, USDC ${usdc/1e9:.1f}B"
                   if usdt is not None and usdc is not None else 'unavailable')

    deriv_status = ctx['derivatives'].get('status', 'unknown')

    portfolio_lines = '\n'.join(
        f"  {a['name']}: {a['qty']:g} @ ${a['price']:,.2f} = ${a['value']:,.0f} ({a['pct']:.1f}%)"
        for a in ctx['portfolio'] if a['value'] > 0
    ) or '  (no holdings data)'

    system_prompt = f"""You are a sharp crypto market analyst and portfolio strategist with access to live market data and web search.

LIVE MARKET DATA:
- BTC price: ${ctx['btc']:,.0f}
- MVRV: {mvrv_str}
- Fear & Greed: {fg_str}
- BTC 30d trend: {pct30_str}
- BTC dominance: {dom_str}
- ETH/BTC ratio: {eth_btc_str}
- SOL/BTC ratio: {sol_btc_str}
- Stablecoin market caps: {stable_str}
- Derivatives data status: {deriv_status}
- Macro (1D returns): {macro_line('qqq','QQQ')} | {macro_line('nvda','NVDA')} | {macro_line('vix','VIX')} | {macro_line('soxx','SOXX')} | {macro_line('us10y','US10Y')}

PORTFOLIO (total ${ctx['portfolio_total']:,.0f}):
{portfolio_lines}"""

    user_prompt = """Analyze the live data above and return RAW JSON only — no markdown code fences, no preamble, no explanation outside the JSON. Match this exact structure:

{
  "regime": "Accumulation | Distribution | Leverage-led pump | Capitulation | Recovery | Alt rotation | No clear edge",
  "action": "Hold | Prepare to trim | Trim 5% | Trim up to plan max | Buy tranche 1 | Buy tranche 2 | Buy tranche 3 | Buy final tranche | Rebuy — upside invalidation | Avoid alts | Watchlist only",
  "confidence": "Low | Medium | High",
  "summary": "2-3 sentence regime summary",
  "evidence": ["up to 5 specific data points"],
  "warning_flags": ["active risks"],
  "opportunity_flags": ["specific opportunities"],
  "biggest_risk": "single biggest risk",
  "next_trigger": "most important level or event to watch",
  "what_would_change_my_mind": "one sentence",
  "scores": {"accumulation": 0-100, "trim": 0-100, "alt_risk": 0-100, "ai_ipo_stress": 0-100, "fragility": 0-100}
}"""

    return system_prompt, user_prompt

def fetch_briefing(system_prompt, user_prompt):
    """Call OpenRouter API server-side with briefing prompts. Expects a raw-JSON
    response per build_briefing_prompts(); falls back to {'raw': text} if the
    model doesn't return valid JSON."""
    import re
    api_key = os.environ.get('OPENROUTER_API_KEY', '').strip()
    if not api_key:
        return {'error': 'OPENROUTER_API_KEY not configured'}

    try:
        r = requests.post(
            'https://openrouter.ai/api/v1/chat/completions',
            headers={
                'Content-Type': 'application/json',
                'Authorization': f'Bearer {api_key}',
                'HTTP-Referer': 'https://srv1710249.hstgr.cloud',
                'X-Title': 'Crypto Command Centre',
            },
            json={
                'model': 'perplexity/sonar-pro',
                'max_tokens': 1200,
                'messages': [
                    {'role': 'system', 'content': system_prompt},
                    {'role': 'user', 'content': user_prompt}
                ]
            },
            timeout=30
        )
        data = r.json()
        if data.get('error'):
            return {'error': data['error'].get('message', 'Unknown API error')}

        raw = data.get('choices', [{}])[0].get('message', {}).get('content', '')
        # Strip Perplexity citation markers [1], [2] etc
        text = re.sub(r'\[\d+\]', '', raw).strip()
        # Strip markdown code fences if the model wrapped the JSON anyway
        fence = re.match(r'^```(?:json)?\s*(.*?)\s*```$', text, re.DOTALL)
        if fence:
            text = fence.group(1).strip()
        try:
            return json.loads(text)
        except (ValueError, TypeError):
            return {'raw': text}
    except Exception as e:
        print(f'OpenRouter briefing error: {e}')
        return {'error': str(e)}

# ─── HTTP HANDLER ─────────────────────────────────────────────
class ProxyHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass

    def send_json(self, data):
        body = json.dumps(data).encode()
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET')
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        path   = self.path.split('?')[0]
        query  = self.path.split('?')[1] if '?' in self.path else ''
        params = dict(p.split('=') for p in query.split('&') if '=' in p)

        if path == '/api/market':
            prices     = fetch_prices() or {}
            sparklines = fetch_sparklines() or []
            metals     = fetch_metals() or {}
            macro      = fetch_macro() or {}
            fg         = fetch_fear_greed() or {}
            news       = fetch_news() or []
            global_data = fetch_global() or {}
            btc_dom    = global_data.get('data', {}).get('market_cap_percentage', {}).get('btc', None)
            mvrv       = cache['mvrv']['data']          # served from cache, warmed in background
            btc_history = get_btc_price_summary()       # reads from cache only, never blocks
            etf_flows   = fetch_etf_flows()
            stablecoins = fetch_stablecoins() or {}
            derivatives = fetch_derivatives() or {}

            # Calculate total portfolio for snapshot
            # Quantities hardcoded here — proxy has no way to know bot PnL
            # Dashboard will call save_portfolio after it knows the full total
            p = prices
            try:
                qty = {
                    'cold_btc':0.3494,'cdc_btc':0.01005554,'cdc_sol':1.5421,
                    'cdc_cro':4064.46,'cdc_jup':453.54,'cdc_akt':77.4597,
                    'cdc_inj':9.3635,'cdc_fet':235.2,'cdc_render':25.363,
                    'cdc_eth':0.02007385,'cdc_sui':29.4464,'cdc_icp':7.5,
                }
                btc  = p.get('bitcoin',{}).get('usd',0)
                sol  = p.get('solana',{}).get('usd',0)
                cro  = p.get('crypto-com-chain',{}).get('usd',0)
                jup  = p.get('jupiter-exchange-solana',{}).get('usd',0)
                akt  = p.get('akash-network',{}).get('usd',0)
                inj  = p.get('injective-protocol',{}).get('usd',0)
                fet  = p.get('fetch-ai',{}).get('usd',0)
                rnd  = p.get('render-token',{}).get('usd',0)
                eth  = p.get('ethereum',{}).get('usd',0)
                sui  = p.get('sui',{}).get('usd',0)
                icp  = p.get('internet-computer',{}).get('usd',0)
                cold_val = qty['cold_btc'] * btc
                cdc_val  = (qty['cdc_btc']*btc + qty['cdc_sol']*sol + qty['cdc_cro']*cro
                           + qty['cdc_jup']*jup + qty['cdc_akt']*akt + qty['cdc_inj']*inj
                           + qty['cdc_fet']*fet + qty['cdc_render']*rnd + qty['cdc_eth']*eth
                           + qty['cdc_sui']*sui + qty['cdc_icp']*icp)
                # Bot capital passed as 0 here — dashboard adds it
                total = cold_val + cdc_val
                if total > 100:
                    save_portfolio_snapshot(total)
            except Exception as e:
                print(f'Portfolio snapshot error: {e}')

            self.send_json({
                'prices':            prices,
                'sparklines':        sparklines,
                'metals':            metals,
                'macro':             macro,
                'fear_greed':        fg,
                'news':              news,
                'btc_dominance':     btc_dom,
                'mvrv':              mvrv,
                'btc_price_history': btc_history,
                'etf_flows':         etf_flows,
                'stablecoins':       stablecoins,
                'derivatives':       derivatives,
                'timestamp':         datetime.utcnow().isoformat(),
            })

        elif path == '/api/btc_chart':
            days = params.get('days', '1')
            data = fetch_btc_chart(days)
            self.send_json(data or {})

        elif path == '/api/ohlc':
            asset = params.get('asset', 'btc')
            days  = params.get('days', '1')
            candles = fetch_ohlc(asset, days)
            self.send_json({'asset': asset, 'days': days, 'candles': candles or []})

        elif path == '/api/portfolio':
            self.send_json(load_portfolio_history())

        else:
            self.send_response(404)
            self.end_headers()

    def do_POST(self):
        path = self.path.split('?')[0]
        if path == '/api/portfolio':
            try:
                length = int(self.headers.get('Content-Length', 0))
                body   = json.loads(self.rfile.read(length))
                total  = body.get('total_usd')
                if total and total > 100:
                    save_portfolio_snapshot(total)
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                self.wfile.write(b'{"ok":true}')
            except Exception as e:
                print(f'Portfolio POST error: {e}')
                self.send_response(400)
                self.end_headers()
        elif path == '/api/briefing':
            try:
                length = int(self.headers.get('Content-Length', 0))
                if length:
                    self.rfile.read(length)  # drain body — prompt is built server-side from live data
                system_prompt, user_prompt = build_briefing_prompts()
                result = fetch_briefing(system_prompt, user_prompt)
                self.send_json(result)
            except Exception as e:
                print(f'Briefing POST error: {e}')
                self.send_json({'error': str(e)})
        else:
            self.send_response(404)
            self.end_headers()

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    daemon_threads = True

def background_worker():
    """Pre-warm caches at startup with staggered delays, then keep all sources
    proactively refreshed so request handlers always serve from cache."""
    import time
    time.sleep(1)
    print('[market_proxy] Background worker started — warming caches')
    # Stagger startup to avoid hammering APIs simultaneously
    for fn in [fetch_prices, fetch_fear_greed, fetch_global,
               fetch_metals, fetch_macro, fetch_sparklines,
               fetch_news, fetch_mvrv, fetch_stablecoins, fetch_derivatives,
               lambda: fetch_btc_chart('1'),
               lambda: fetch_btc_chart('30'),
               lambda: fetch_ohlc('btc', '1'),
               lambda: fetch_ohlc('sol', '1'),
               lambda: fetch_ohlc('gold', '1'),
               lambda: fetch_ohlc('spy', '1'),
               lambda: fetch_ohlc('nvda', '1'),
               lambda: fetch_ohlc('vix', '1')]:
        try:
            fn()
            time.sleep(3)
        except Exception as e:
            print(f'Warmup error: {e}')
    print('[market_proxy] Cache warm-up complete')

    iteration = 0
    while True:
        time.sleep(30)
        iteration += 1
        try:
            fetch_prices()                    # every 30s — keeps price cache always fresh
            if iteration % 4 == 0:            # every 2 min
                fetch_news()
            if iteration % 10 == 0:           # every 5 min
                fetch_sparklines()
                fetch_metals()
                fetch_macro()
                fetch_global()
                fetch_fear_greed()
                fetch_btc_chart('30')
                fetch_ohlc('btc', '1')        # keep 1D candles warm for all 6 panels
                fetch_ohlc('sol', '1')
                fetch_ohlc('gold', '1')
                fetch_ohlc('spy', '1')
                fetch_ohlc('nvda', '1')
                fetch_ohlc('vix', '1')
            if iteration % 20 == 0:           # every 10 min
                fetch_derivatives()
            if iteration % 60 == 0:           # every 30 min
                fetch_btc_chart('1')
            if iteration % 120 == 0:          # every hour
                fetch_mvrv()
            if iteration % 480 == 0:          # every 4 hours
                fetch_stablecoins()
        except Exception as e:
            print(f'Background refresh error: {e}')

def run():
    print(f'[market_proxy] Starting on port {PORT}')
    threading.Thread(target=background_worker, daemon=True).start()
    server = ThreadedHTTPServer(('0.0.0.0', PORT), ProxyHandler)
    server.serve_forever()

if __name__ == '__main__':
    run()
