#!/usr/bin/env python3
"""Fetch open TastyTrade positions and save underlying symbols to /tmp/tt_positions.json"""
import json, subprocess, urllib.request, urllib.parse, sys

CLIENT_SECRET = "c2be8b046d2f84466024a14b6339dee9d262d3a6"
REFRESH_TOKEN = "eyJhbGciOiJFZERTQSIsInR5cCI6InJ0K2p3dCIsImtpZCI6IjQ2UVFzMzZ2SHp3QUpjOXpMR0RrQW5hN3NPVm1MMm9raXYyNDFaWmZPLXciLCJqa3UiOiJodHRwczovL2FwaS50YXN0eXRyYWRlLmNvbS9vYXV0aC9qd2tzIn0.eyJpc3MiOiJodHRwczovL2FwaS50YXN0eXRyYWRlLmNvbSIsInN1YiI6IlVhYzY3ZDNlNi1hMmZmLTRlOWItODViNC0wZWNjMGU4NDVlOTYiLCJpYXQiOjE3NzYxNjM5MTcsImF1ZCI6ImNkZTllMjM3LWEyNWQtNGYxOS1iNjhhLWY0N2M4MWQ3YzE5YyIsImdyYW50X2lkIjoiR2JkZjE1YzJkLWM4MTEtNGM1MC04MDMyLTZkMDdhYjdkM2M1NCIsInNjb3BlIjoicmVhZCB0cmFkZSBvcGVuaWQifQ.SkpngdxhU5pQdOdEq8UXIBLPQLtIMLDNG-EUsoK66XUhIa26GgvDRUd5ya7l_LsdCSCnP6U77zNB_vq4JSN6CA"
ACCOUNT_NUMBER = "5WI14075"
BASE_URL = "https://api.tastytrade.com"

# 1. Get access token via OAuth refresh
body = urllib.parse.urlencode({
    "grant_type": "refresh_token",
    "refresh_token": REFRESH_TOKEN,
    "client_secret": CLIENT_SECRET,
    "scope": "read trade openid",
}).encode()

req = urllib.request.Request(
    f"{BASE_URL}/oauth/token",
    data=body,
    headers={
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/json",
        "User-Agent": "hermes-reports",
    },
    method="POST",
)
with urllib.request.urlopen(req, timeout=15) as resp:
    token_data = json.load(resp)

access_token = token_data["access_token"]

# 2. Fetch open positions
req2 = urllib.request.Request(
    f"{BASE_URL}/accounts/{ACCOUNT_NUMBER}/positions",
    headers={
        "Authorization": f"Bearer {access_token}",
        "Accept": "application/json",
        "User-Agent": "hermes-reports",
    },
)
with urllib.request.urlopen(req2, timeout=15) as resp:
    positions_data = json.load(resp)

items = positions_data.get("data", {}).get("items", [])

# Extract unique underlying symbols
underlyings = sorted(set(p["underlying-symbol"] for p in items if p.get("underlying-symbol")))

out = {"underlyings": underlyings, "positions": items}
with open("/tmp/tt_positions.json", "w") as f:
    json.dump(out, f)

print(f"Fetched {len(items)} positions across {len(underlyings)} underlyings: {', '.join(underlyings)}")
