#!/usr/bin/env python3
"""
Fetch current TSX stock prices via TMX Money GraphQL and write live_prices.json.
TMX Money is the official TSX exchange data API — no auth needed server-side.

Run manually:  python3 fetch_prices.py
Cron (every 5 min on weekdays during market hours):
  */5 9-16 * * 1-5 /usr/bin/python3 /media/usb/claude/SwingTrader/fetch_prices.py >> /media/usb/claude/SwingTrader/daily_run.log 2>&1
"""
import json, sys, urllib.request
from datetime import datetime, timezone
from pathlib import Path

BASE           = Path(__file__).parent
positions_file = BASE / 'positions.json'
output_file    = BASE / 'live_prices.json'

with open(positions_file) as f:
    data = json.load(f)

tickers = [
    p['ticker'] for p in data.get('open_positions', [])
    if not p.get('_example') and p.get('ticker')
]

prices = {}
for ticker in tickers:
    sym = ticker.split('.')[0].upper()   # SU.TO → SU
    body = json.dumps({
        'operationName': 'getQuoteBySymbol',
        'variables':     {'symbol': sym, 'locale': 'en'},
        'query':         'query getQuoteBySymbol($symbol:String,$locale:String){getQuoteBySymbol(symbol:$symbol,locale:$locale){symbol price percentChange}}',
    }).encode()
    req = urllib.request.Request(
        'https://app-money.tmx.com/graphql',
        data=body,
        headers={'Content-Type': 'application/json', 'Accept': 'application/json'},
        method='POST',
    )
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            raw = json.loads(resp.read())
        q     = raw.get('data', {}).get('getQuoteBySymbol', {})
        price = q.get('price')
        chg   = q.get('percentChange')
        if price is not None:
            prices[ticker.upper()] = {'price': float(price), 'changePct': float(chg) if chg is not None else None}
    except Exception as e:
        print(f'[fetch_prices] {ticker}: {e}', file=sys.stderr)

output = {
    'last_updated': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
    'prices':       prices,
}
with open(output_file, 'w') as f:
    json.dump(output, f, indent=2)

now = datetime.now().strftime('%H:%M:%S')
print(f'[fetch_prices] {now} — {len(prices)}/{len(tickers)} prices: ' +
      ', '.join(f"{t}=${v["price"]:.2f}" for t, v in prices.items()))
