#!/usr/bin/env python3
"""Driver for the picard1701 /q quest. Uses real curl (server checks UA)."""
import base64, subprocess, sys, os, re, urllib.parse

HERE = os.path.dirname(os.path.abspath(__file__))
SID = os.path.join(HERE, 'sid.txt')

def curl(url):
    r = subprocess.run(['curl', '-sS', url], capture_output=True, text=True, timeout=45)
    return r.stdout

def try_all(data):
    outs = []
    for name, fn in (('b64', base64.b64decode), ('b85', base64.b85decode), ('a85', base64.a85decode)):
        try:
            d = fn(data)
            if d:
                outs.append((name, d))
        except Exception:
            pass
    return outs

def unwrap(data, depth, path=()):
    if depth == 0:
        try:
            t = data.decode('utf-8')
        except UnicodeDecodeError:
            return None
        if not all(c == '\n' or c == '\t' or 32 <= ord(c) < 127 or ord(c) > 160 for c in t):
            return None
        return (path, t)
    for name, d in try_all(data):
        r = unwrap(d, depth - 1, path + (name,))
        if r:
            return r
    return None

def decode_q(blob):
    raw = blob.strip().encode()
    for depth in (5, 4, 3, 2, 1):
        r = unwrap(raw, depth)
        if r:
            return f'[{" -> ".join(r[0])}] {r[1]}'
    return '<<UNDECODED>> ' + blob

def show(body):
    print(body_without_q := re.sub(r'^Question:.*$', '', body, flags=re.M).rstrip())
    m = re.search(r'^Session ID:\s*(\S+)', body, re.M)
    if m:
        open(SID, 'w').write(m.group(1))
    q = re.search(r'^Question:\s*(\S+)\s*$', body, re.M)
    if q:
        print('\n>>> QUESTION:', decode_q(q.group(1)))

if __name__ == '__main__':
    if sys.argv[1] == 'start':
        show(curl('https://picard1701.com/q'))
    else:
        sid = open(SID).read().strip()
        ans = urllib.parse.quote(' '.join(sys.argv[1:]))
        show(curl(f'https://picard1701.com/q?sid={sid}&answer={ans}'))
