#!/usr/bin/env python3
"""Solve the star.py question: download fresh, extract magic, run, submit token."""
import base64, re, subprocess, os, sys, urllib.parse

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from q import curl, show, SID

path = os.path.join(HERE, 'star_fresh.py')
subprocess.run(['curl', '-sS', 'https://picard1701.com/star.py', '-o', path], check=True)

src = open(path).read()
v = re.search(r'voyager\s*=\s*"([^"]+)"', src).group(1)
magic = base64.b64decode(base64.b64decode(v)).decode().strip()
value = magic.split(':', 1)[1].strip() if ':' in magic else magic
print('magic =', repr(magic), '-> arg =', repr(value))

out = subprocess.run(['python3.14', path, value], capture_output=True, text=True, timeout=45)
lines = [l for l in out.stdout.strip().splitlines() if l.strip()]
print('stdout lines:', lines)
token = lines[-1].strip()
if token == magic:
    sys.exit('ERROR: only the decoy line was printed; no token found. stderr=' + out.stderr[:500])
print('answer token =', repr(token))

sid = open(SID).read().strip()
show(curl(f'https://picard1701.com/q?sid={sid}&answer={urllib.parse.quote(token)}'))
