#!/usr/bin/env python3
# tkrec — ติดคีบทัวร์นาเมนต์ live recorder (runs 24/7 on the Lightsail box)
# v7 (5 Nov 2026): records the sharpest stream TikTok offers (probes every pull URL), remote 'probe' op to test it
# - polls TikTok every 10 s for @UNIQUE_ID; when live, asks the logged-in Chrome (CDP :9222) for the stream URL
# - records with ffmpeg as 6-s HLS segments, part by part; a dropped stream is re-fetched and continued, nothing already on disk is lost
# - uploads finished segments to tidkeep KV (rec:<slug>/...) while recording, writes live.m3u8 every few seconds and the VOD playlist at the end
# - writes its status to KV key tkrec:status so it can be monitored without SSH
# v6: parallel uploads + throttled status; full.mp4 made at once from local parts; unfinished uploads resumed after a restart;
#     ops setkey / clip; after each live the highlight-clip job (Claude Code, owner's API key) starts by itself in its own systemd unit
import os, sys, json, time, re, subprocess, threading, datetime, urllib.request, urllib.parse, base64, traceback, secrets, concurrent.futures
HOME = os.path.expanduser('~'); CFG = json.load(open(os.path.join(HOME, '.tkrec', 'config.json')))
UID = CFG['uniqueId']; ROOT = os.path.join(HOME, 'tkrec'); REC = os.path.join(ROOT, 'rec'); os.makedirs(REC, exist_ok=True)
RECKEY = CFG['rec_key']; SITE = CFG.get('site', 'https://tidkeep.owen-t.com')
BKK = datetime.timezone(datetime.timedelta(hours=7))
def now(): return datetime.datetime.now(BKK)
def log(*a):
    s = now().strftime('%d/%m %H:%M:%S ') + ' '.join(str(x) for x in a); print(s, flush=True)
    with open(os.path.join(ROOT, 'tkrec.log'), 'a') as f: f.write(s + '\n')
STATUS = {'uid': UID, 'state': 'idle', 'since': now().isoformat(), 'slug': None, 'parts': 0, 'segments': 0, 'uploaded': 0, 'chrome': None, 'err': None}
def kv_put(key, data, ctype):
    """Upload through the tidkeep site (POST /api/rec/put, REC_KEY) — key is 'tkrec:status' or '<slug>/<file>' (stored as rec:<slug>/<file>)."""
    k = key[4:] if key.startswith('rec:') else key
    for a in range(4):
        try:
            req = urllib.request.Request(SITE + '/api/rec/put?' + urllib.parse.urlencode({'k': k, 'type': ctype}), data=data, method='POST')
            req.add_header('x-rec-key', RECKEY); req.add_header('content-type', ctype); req.add_header('User-Agent', 'tkrec/1')
            with urllib.request.urlopen(req, timeout=120) as r:
                if json.loads(r.read().decode()).get('ok'): return True
        except Exception as e: log('upload', k, 'retry', a, str(e)[:120])
        time.sleep(3)
    return False
_last_push = [0.0]; _push_lock = threading.Lock()
def push_status(force=True, **kw):
    with _push_lock:
        STATUS.update(kw)
        if not force and time.time() - _last_push[0] < 10: return
        STATUS['at'] = now().isoformat(); _last_push[0] = time.time(); body = json.dumps(STATUS, ensure_ascii=False).encode()
    try: kv_put('tkrec:status', body, 'application/json')
    except Exception: pass
def room_status():
    try:
        req = urllib.request.Request(f'https://www.tiktok.com/api-live/user/room/?aid=1988&uniqueId={UID}&sourceType=54',
                                     headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)'})
        with urllib.request.urlopen(req, timeout=15) as r: d = json.loads(r.read().decode())['data']
        return int(d['user'].get('status') or 0), str(d['user'].get('roomId') or '')
    except Exception as e: return -1, str(e)[:80]
def probe_stream(u):
    """(width*height, bitrate) of one pull URL, (0, 0) if it does not answer in time"""
    try:
        out = subprocess.run(['ffprobe', '-v', 'error', '-rw_timeout', '8000000', '-analyzeduration', '3000000', '-probesize', '3000000',
                              '-select_streams', 'v:0', '-show_entries', 'stream=width,height,bit_rate:format=bit_rate', '-of', 'json', u],
                             capture_output=True, text=True, timeout=20).stdout
        j = json.loads(out or '{}'); st = (j.get('streams') or [{}])[0]
        w, h = int(st.get('width') or 0), int(st.get('height') or 0)
        br = int(st.get('bit_rate') or (j.get('format') or {}).get('bit_rate') or 0)
        return w * h, br, f'{w}x{h}'
    except Exception:
        return 0, 0, '?'
LAST_Q = []
def best_stream(urls, fallback):
    """v7: TikTok offers the live in several qualities - probe every pull URL and record the sharpest one (largest picture, then highest bitrate)"""
    res = []
    for u in urls[:8]:
        a, br, wh = probe_stream(u); res.append((a, br, wh, u))
    res.sort(key=lambda x: (x[0], x[1]), reverse=True)
    global LAST_Q; LAST_Q = [f"{wh}@{br//1000}k" for a, br, wh, u in res]
    try: log('stream qualities:', ', '.join(f"{wh}@{br//1000}k" for a, br, wh, u in res))
    except Exception: pass
    if res and res[0][0] > 0:
        try: push_status(quality=res[0][2])
        except Exception: pass
        return res[0][3]
    return fallback
def stream_url(uid=None):
    uid = uid or UID
    """Ask the logged-in Chrome (remote debugging on :9222) for the live pull URL. Returns (flv, err)."""
    try:
        from playwright.sync_api import sync_playwright
        with sync_playwright() as p:
            b = p.chromium.connect_over_cdp('http://127.0.0.1:9222', timeout=15000)
            ctx = b.contexts[0] if b.contexts else b.new_context()
            pg = ctx.new_page(); pg.goto('https://www.tiktok.com/live', wait_until='domcontentloaded', timeout=45000)
            js = """async (u) => { const d = await fetch('/api-live/user/room/?aid=1988&uniqueId='+u+'&sourceType=54',{credentials:'include'}).then(r=>r.json());
              const lr = d.data.liveRoom||{}; const sd = lr.streamData; if(!sd) return {err:'no stream (not logged in or age gate)', status:d.data.user.status};
              const txt = JSON.stringify(sd).replace(/\\\\u002F/g,'/').replace(/\\\\/g,''); const urls = txt.match(/https:\\/\\/[^"'\\s]+?\\.flv[^"'\\s]*/g) || [];
              const pick = urls.find(x=>x.includes('_hd')) || urls.find(x=>x.includes('_sd')) || urls[0]; return pick ? {flv:pick, n:urls.length, all:[...new Set(urls)]} : {err:'no flv url in streamData', status:d.data.user.status}; }"""
            r = pg.evaluate(js, uid); pg.close()
            if r.get('flv'): return best_stream(r.get('all') or [r['flv']], r['flv']), None
            return None, r.get('err', 'unknown')
    except Exception as e: return None, 'chrome: ' + str(e)[:160]
def ffmpeg_part(url, d, part):
    cmd = ['ffmpeg', '-nostdin', '-hide_banner', '-loglevel', 'warning', '-rw_timeout', '20000000', '-i', url, '-map', '0:v:0', '-map', '0:a:0?', '-sn', '-dn', '-c', 'copy',
           '-f', 'hls', '-hls_time', '6', '-hls_list_size', '0', '-hls_segment_filename', f'{d}/{part}_%05d.ts', f'{d}/{part}.m3u8']
    with open(f'{d}/ffmpeg.log', 'a') as lf: return subprocess.call(cmd, stdout=lf, stderr=lf)
class Uploader(threading.Thread):
    def __init__(self, slug, d): super().__init__(daemon=True); self.slug, self.d, self.done, self.stop = slug, d, set(), False
    def listed(self):
        out = []
        for pl in sorted(f for f in os.listdir(self.d) if re.match(r'p\d+\.m3u8$', f)):
            for line in open(os.path.join(self.d, pl)):
                line = line.strip()
                if line.endswith('.ts'): out.append(line)
        return out
    def live_playlist(self):
        segs = []; tgt = 6
        for pl in sorted(f for f in os.listdir(self.d) if re.match(r'p\d+\.m3u8$', f)):
            lines = [l.strip() for l in open(os.path.join(self.d, pl))]; dur = None
            for l in lines:
                if l.startswith('#EXT-X-TARGETDURATION'): tgt = max(tgt, int(l.split(':')[1]))
                if l.startswith('#EXTINF'): dur = l
                elif l.endswith('.ts') and l in self.done: segs.append((dur, l))
        tail = segs[-6:]
        if not tail: return None
        seq = max(0, len(segs) - len(tail))
        return '\n'.join(['#EXTM3U', '#EXT-X-VERSION:3', f'#EXT-X-TARGETDURATION:{tgt}', f'#EXT-X-MEDIA-SEQUENCE:{seq}'] + [x for d_, s in tail for x in (d_, f'/v/{self.slug}/{s}')]) + '\n'
    def run(self):
        last_live = 0; pool = concurrent.futures.ThreadPoolExecutor(3)
        def one(f):
            return f if kv_put(f'rec:{self.slug}/{f}', open(os.path.join(self.d, f), 'rb').read(), 'video/mp2t') else None
        while True:
            todo = [f for f in self.listed() if f not in self.done]
            for k in range(0, len(todo), 6):
                for r in pool.map(one, todo[k:k + 6]):
                    if r: self.done.add(r)
                push_status(force=False, uploaded=len(self.done), segments=len(self.listed()))
                if time.time() - last_live > 5:
                    pl = self.live_playlist()
                    if pl and not self.stop: kv_put(f'rec:{self.slug}/live.m3u8', pl.encode(), 'application/vnd.apple.mpegurl'); last_live = time.time()
            if todo: push_status(uploaded=len(self.done), segments=len(self.listed()))
            if time.time() - last_live > 4 and not self.stop:
                pl = self.live_playlist()
                if pl: kv_put(f'rec:{self.slug}/live.m3u8', pl.encode(), 'application/vnd.apple.mpegurl'); last_live = time.time()
            if self.stop and all(f in self.done for f in self.listed()):
                out = ['#EXTM3U', '#EXT-X-VERSION:3', '#EXT-X-PLAYLIST-TYPE:VOD']; tgt = 6; body = []
                pls = sorted(f for f in os.listdir(self.d) if re.match(r'p\d+\.m3u8$', f))
                for i, pl in enumerate(pls):
                    lines = [l.strip() for l in open(os.path.join(self.d, pl))]
                    for l in lines:
                        if l.startswith('#EXT-X-TARGETDURATION'): tgt = max(tgt, int(l.split(':')[1]))
                    if i > 0: body.append('#EXT-X-DISCONTINUITY')
                    for l in lines:
                        if l.startswith('#EXTINF'): body.append(l)
                        elif l.endswith('.ts'): body.append(f'/v/{self.slug}/{l}')
                out.insert(2, f'#EXT-X-TARGETDURATION:{tgt}'); out += body + ['#EXT-X-ENDLIST']
                ok = kv_put(f'rec:{self.slug}/index.m3u8', '\n'.join(out).encode() + b'\n', 'application/vnd.apple.mpegurl')
                open(os.path.join(self.d, 'UPLOADED'), 'w').write(str(ok)); log('VOD playlist uploaded', ok, len(self.done), 'segments'); return
            time.sleep(5)
def make_full(d):
    if os.path.exists(f'{d}/full.mp4') and os.path.getsize(f'{d}/full.mp4') > 1000: return True
    try: subprocess.call(['bash', '-c', f'ffmpeg -nostdin -loglevel error -y -i "concat:$(ls {d}/p*_*.ts | sort | tr "\\n" "|" | sed "s/|$//")" -c copy {d}/full.tmp.mp4 && mv {d}/full.tmp.mp4 {d}/full.mp4'])
    except Exception: pass
    return os.path.exists(f'{d}/full.mp4')
def finish_live(slug, d, up):
    """Runs in the background so a new live (next player) is picked up immediately."""
    ok = make_full(d); log('full.mp4', slug, ok)
    if ok and CFG.get('autoclip', True):
        nf = os.path.join(HOME, '.tkrec', 'clipnotes.txt')
        start_clip(slug, {'notes': open(nf).read().strip() if os.path.exists(nf) else ''})
    up.join(timeout=3 * 3600)
    log('finished', slug)
def record_live(room0):
    slug = 'r-' + now().strftime('%y%m%d-%H%M'); d = os.path.join(REC, slug); os.makedirs(d, exist_ok=True)
    open(os.path.join(d, 'START'), 'w').write(now().isoformat())
    log('LIVE start', slug, 'room', room0); push_status(state='live', slug=slug, room=room0, parts=0, segments=0, uploaded=0, err=None)
    up = Uploader(slug, d); up.start(); n = 0; miss = 0
    while True:
        url, err = stream_url()
        if not url:
            log('no stream url:', err); push_status(err=err, chrome='fail' if err.startswith('chrome') else 'ok')
            st, room = room_status()
            if st != 2 or room != room0: miss += 1
            if miss >= 6: break
            time.sleep(10); continue
        push_status(chrome='ok', err=None)
        n += 1; part = f'p{n:02d}'; push_status(parts=n)
        rc = ffmpeg_part(url, d, part); log('ffmpeg', part, 'ended rc', rc)
        time.sleep(3)
        st, room = room_status()
        if st == 2 and room != room0: log('new live room', room, '- closing', slug); break   # next player started a new live
        if st != 2:
            for k in range(6):   # 60 s grace: TikTok can flip to 4 for a moment
                time.sleep(10); st, room = room_status()
                if st == 2: break
            if st != 2 or room != room0: break
    open(os.path.join(d, 'DONE'), 'w').write(now().isoformat()); up.stop = True; log('LIVE over', slug, 'parts', n)
    push_status(state='idle', slug=slug)
    threading.Thread(target=finish_live, args=(slug, d, up), daemon=True).start()
# ---------- highlight-clip job (v6) ----------
CLIPS = os.path.join(HOME, 'clips'); ENVF = os.path.join(HOME, '.anthropic_env')
CLIPJOB = r"""#!/bin/bash
# clipjob.sh <slug> — runs Claude Code headless on one recording, then uploads the results (written by tkrec v6)
S="$1"; OUT="$HOME/clips/$S"; mkdir -p "$OUT"; cd /home/claude/review/mg || exit 1
exec 9>"$HOME/clips/.lock"; echo "queued $(date -Iseconds)" > "$OUT/STATE"; flock 9   # one clip job at a time (4 GB box)
set -a; . "$HOME/.anthropic_env"; set +a
echo "running $(date -Iseconds)" > "$OUT/STATE"
( while [ -f "$OUT/STATE" ] && grep -q running "$OUT/STATE"; do python3 "$HOME/tkrec/tkrec.py" clipbeat "$S" >/dev/null 2>&1; sleep 120; done ) &
nice -n 15 claude -p "$(cat "$OUT/prompt.txt")" --model opus --dangerously-skip-permissions --output-format stream-json --verbose > "$OUT/claude.jsonl" 2> "$OUT/claude.err"
echo "finished rc=$? $(date -Iseconds)" > "$OUT/STATE"
python3 "$HOME/tkrec/tkrec.py" pushclip "$S"
"""
PROMPT = """You are running UNATTENDED on Owen's AWS box (no one can answer questions — never ask, write doubts into the report instead).
Read /home/claude/CLAUDE.md first and follow every rule in it exactly; it is Owen's standard and he rejects anything that breaks it.

Recording to use: {recfile}  (HLS parts in {rec}/p*_*.ts, 5.88 s each; part p01 segment 0 starts at {start}; recording ended {end}).
Extra facts from Owen / the operator (treat as ground truth): {notes}
{picks}
Job:
1. Work out which scheduled player(s) of ติดคีบทัวร์นาเมนต์ Round 2 appear in this recording and, from the host's voice, when each player's REAL match starts and ends (practice is not used). Use faster-whisper 'small' int8 with vad to scan, and 'medium' only on short windows for final word timestamps — the box has 2 vCPUs and also records lives, so keep heavy steps under nice and never run two whisper jobs at once.
2. For each player found, find every catch (doll really falls into the chute — verify frame by frame), near-misses and the last 2–3 nudging tries, the closing count, and standout spoken lines.
3. For each player build the highlight clip in the approved style of plan_1026g.json (พี่เบนซ์): copy it to plan_<who>.json, add the footage to SRC in build2.py, avatar av_<who>.jpg (download the face picture from {avurl}<who>.jpg if not present), closing scoreboard = one continuous list of all Round 2 players so far (rows in plan_1026g.json plus the new players) with the day's player inserted at its rank.
   Output files go to {out}/ :  <who>_candidates.txt (numbered standout-line candidates: time, exact words), <who>_{kind}.mp4 (the clip), and report.txt in Thai (players, match start/end clock times, doll count, list of catches with times, anything doubtful).
4. Before finishing, check each clip yourself as CLAUDE.md rule 10 says (contact sheet + sync) and fix what is wrong. Do not touch tkrec, the website, LINE or anything outside the clip work.
"""
def start_clip(slug, c):
    """Write the prompt for this recording and start clipjob.sh in its own systemd unit (survives tkrec restarts)."""
    if not os.path.exists(ENVF): log('clip: no API key yet'); return 'no key'
    d = os.path.join(REC, slug); who = re.sub(r'[^a-z0-9]', '', c.get('who', ''))[:12]; jid = slug + ('-' + who if who else '')
    out = os.path.join(CLIPS, jid); os.makedirs(out, exist_ok=True)
    rf = os.path.join(d, 'full.mp4')
    if c.get('range'):   # a cut of the still-running recording, e.g. one player's part: segments a..b of p01
        a, b = int(c['range'][0]), int(c['range'][1]); rf = os.path.join(d, f"cut_{c.get('who', 'x')}_{a}_{b}.mp4")
        segs = '|'.join(os.path.join(d, f'p01_{i:05d}.ts') for i in range(a, b + 1) if os.path.exists(os.path.join(d, f'p01_{i:05d}.ts')))
        subprocess.call(['ffmpeg', '-nostdin', '-loglevel', 'error', '-y', '-i', 'concat:' + segs, '-c', 'copy', rf])
    elif not os.path.exists(rf): make_full(d)
    tokf = os.path.join(out, '.tok')
    if not os.path.exists(tokf): open(tokf, 'w').write(secrets.token_hex(4))
    rd = lambda f: open(os.path.join(d, f)).read().strip() if os.path.exists(os.path.join(d, f)) else c.get(f.lower(), '?')
    picks = c.get('picks')
    pr = PROMPT.format(rec=d, recfile=rf, start=c.get('start') or rd('START'), end=c.get('end') or rd('DONE'), notes=c.get('notes') or 'none',
                       picks=('Owen has picked these standout lines (use exactly these, rebuild the clips as FINAL): ' + picks) if picks else 'Owen has not picked standout lines yet: build a DRAFT using your best candidates.',
                       avurl='https://img.owen-t.com/tk-0418ae8bf227/av_', out=out, kind='final' if picks else 'draft')
    open(os.path.join(out, 'prompt.txt'), 'w').write(pr)
    job = os.path.join(ROOT, 'clipjob.sh'); open(job, 'w').write(CLIPJOB); os.chmod(job, 0o755)
    unit = 'clipjob-' + jid + '-' + now().strftime('%H%M%S')
    rc = subprocess.call(['systemd-run', '--user', '--collect', '--unit', unit, '--working-directory=/home/claude/review/mg', job, jid])
    if rc != 0: subprocess.Popen([job, jid], start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL); unit += ' (popen)'
    log('clip job started', jid, unit); clip_put(jid, 'status.txt', ('started ' + now().isoformat() + ' ' + unit).encode()); return unit + ' key ' + clip_key(jid)
def start_job(c):
    """v8: a general unattended Claude Code job on Owen's API key — prompt from the command, input files only from img.owen-t.com (no shell from the command)."""
    if not os.path.exists(ENVF): return 'no key'
    jid = c.get('jid', '')
    if not re.match(r'^[a-z0-9][a-z0-9-]{2,39}$', jid): return 'bad jid'
    out = os.path.join(CLIPS, jid); inp = os.path.join(out, 'in'); os.makedirs(inp, exist_ok=True); got = []
    for a in c.get('assets', []):
        u, n = str(a.get('url', '')), str(a.get('name', ''))
        if not u.startswith('https://img.owen-t.com/') or not re.match(r'^[A-Za-z0-9_.-]{1,60}$', n): continue
        try:
            req = urllib.request.Request(u, headers={'User-Agent': 'tkrec/1'})
            with urllib.request.urlopen(req, timeout=120) as r: open(os.path.join(inp, n), 'wb').write(r.read()); got.append(n)
        except Exception as e: log('job asset', n, str(e)[:100])
    tokf = os.path.join(out, '.tok')
    if not os.path.exists(tokf): open(tokf, 'w').write(secrets.token_hex(4))
    pr = ('You are running UNATTENDED on Owen\'s AWS box (no one can answer questions — never ask, write doubts into report.txt instead).\n'
          f'Input files (downloaded for you): {inp}/ : {", ".join(got) or "none"}\nWrite every deliverable into {out}/ (top level; mp4 under 19 MB each) plus report.txt in Thai.\n'
          'Do not touch tkrec, the website, LINE or anything outside this job.\n\n' + str(c.get('prompt', '')))
    open(os.path.join(out, 'prompt.txt'), 'w').write(pr)
    job = os.path.join(ROOT, 'clipjob.sh'); open(job, 'w').write(CLIPJOB); os.chmod(job, 0o755)
    unit = 'clipjob-' + jid + '-' + now().strftime('%H%M%S')
    rc = subprocess.call(['systemd-run', '--user', '--collect', '--unit', unit, '--working-directory=/home/claude/review/mg', job, jid])
    if rc != 0: subprocess.Popen([job, jid], start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL); unit += ' (popen)'
    log('job started', jid, unit, got); clip_put(jid, 'status.txt', ('started ' + now().isoformat() + ' ' + unit).encode()); return unit + ' key ' + clip_key(jid) + ' assets ' + str(len(got))
def clip_key(slug): return 'clip-' + slug + '-' + open(os.path.join(CLIPS, slug, '.tok')).read().strip()
def clip_put(slug, name, data, ctype='text/plain; charset=utf-8'):
    try: return kv_put(f'rec:{clip_key(slug)}/{name}', data, ctype)
    except Exception as e: log('clip_put', name, str(e)[:100]); return False
def clip_beat(slug):
    out = os.path.join(CLIPS, slug); st = open(os.path.join(out, 'STATE')).read().strip() if os.path.exists(os.path.join(out, 'STATE')) else '?'
    last = ''
    try:
        lines = open(os.path.join(out, 'claude.jsonl')).read().splitlines()
        for l in reversed(lines):
            try: e = json.loads(l)
            except Exception: continue
            if e.get('type') == 'assistant':
                for b in e['message'].get('content', []):
                    if b.get('type') == 'text': last = 'text: ' + b['text'][:300]; break
                    if b.get('type') == 'tool_use': last = 'tool: ' + json.dumps(b.get('input'), ensure_ascii=False)[:300]; break
                if last: break
        n = len(lines)
    except Exception: n = 0
    files = ' '.join(sorted(f for f in os.listdir(out) if not f.startswith('.')))
    clip_put(slug, 'status.txt', f'{now().isoformat()} | {st} | events {n} | files: {files}\n{last}'.encode())
def push_clip(slug):
    out = os.path.join(CLIPS, slug); man = []
    for f in sorted(os.listdir(out)):
        if f.startswith('.') or not re.match(r'^[A-Za-z0-9_.-]{3,50}$', f): continue
        if not re.search(r'\.(mp4|txt|json|jpg|png|md|err|jsonl)$', f) and f != 'STATE': continue
        data = open(os.path.join(out, f), 'rb').read(); ct = 'video/mp4' if f.endswith('.mp4') else ('image/jpeg' if f.endswith('.jpg') else 'text/plain; charset=utf-8')
        parts = [data[i:i + 20_000_000] for i in range(0, len(data), 20_000_000)] or [b'']
        ok = all(clip_put(slug, f if len(parts) == 1 else f'{f}.p{k:02d}', b, ct) for k, b in enumerate(parts))
        man.append({'f': f, 'bytes': len(data), 'parts': len(parts), 'ok': ok})
    clip_put(slug, 'manifest.json', json.dumps({'at': now().isoformat(), 'files': man}, ensure_ascii=False).encode(), 'application/json')
    clip_beat(slug); log('clip results uploaded', slug, len(man))
def set_key(c):
    k = (c.get('key') or '').strip(); w = (c.get('ws') or '').strip()
    if not re.match(r'^sk-ant-[A-Za-z0-9_-]{20,}$', k) or (w and not re.match(r'^wrkspc_[A-Za-z0-9]{10,}$', w)): return {'err': 'bad key/ws format'}
    old = os.umask(0o077)
    try:
        with open(ENVF, 'w') as f:
            f.write(f"export ANTHROPIC_API_KEY='{k}'\n")
            if w: f.write(f"export ANTHROPIC_CUSTOM_HEADERS='anthropic-workspace-id: {w}'\n")
    finally: os.umask(old)
    try:
        req = urllib.request.Request('https://api.anthropic.com/v1/models', headers=dict({'x-api-key': k, 'anthropic-version': '2023-06-01'}, **({'anthropic-workspace-id': w} if w else {})))
        with urllib.request.urlopen(req, timeout=20) as r: code = r.status
    except urllib.error.HTTPError as e: code = e.code
    except Exception as e: code = str(e)[:80]
    v = subprocess.run(['bash', '-lc', 'claude --version'], capture_output=True, text=True).stdout.strip()
    return {'keytest': code, 'claude': v}
def resume_unfinished():
    """After a restart: finish uploads/full.mp4 of recordings whose live ended but whose upload was cut off."""
    for slug in sorted(os.listdir(REC)):
        d = os.path.join(REC, slug)
        if os.path.isdir(d) and os.path.exists(os.path.join(d, 'DONE')) and not os.path.exists(os.path.join(d, 'UPLOADED')):
            log('resume upload', slug); up = Uploader(slug, d); up.stop = True; up.start()
            threading.Thread(target=make_full, args=(d,), daemon=True).start()
def login_check():
    """Which TikTok account is signed in on the recorder's Chrome (age-restricted lives need one)."""
    try:
        from playwright.sync_api import sync_playwright
        with sync_playwright() as p:
            b = p.chromium.connect_over_cdp('http://127.0.0.1:9222', timeout=15000)
            pages = [x for c in b.contexts for x in c.pages if 'tiktok.com' in x.url]
            pg = pages[0] if pages else b.contexts[0].new_page()
            if 'tiktok.com' not in pg.url: pg.goto('https://www.tiktok.com/', wait_until='domcontentloaded', timeout=45000)
            r = pg.evaluate("""async()=>{try{const d=await fetch('/passport/web/account/info/?aid=1459',{credentials:'include'}).then(r=>r.json()); return d&&d.data&&d.data.username ? d.data.username : ''}catch(e){return 'ERR '+e}}""")
            return r or 'LOGGED-OUT'
    except Exception as e: return 'chrome: ' + str(e)[:120]
UPDATE_URL = 'https://img.owen-t.com/tk-0418ae8bf227/tkrec-latest.py'
def get_cmd():
    try:
        req = urllib.request.Request(SITE + '/api/rec/cmd', headers={'x-rec-key': RECKEY, 'User-Agent': 'tkrec/1'})
        with urllib.request.urlopen(req, timeout=15) as r: return json.loads(r.read().decode()).get('cmd')
    except Exception: return None
def run_cmd(c):
    """Fixed set of remote operations only (no arbitrary shell)."""
    op = c.get('op'); res = {'id': c.get('id'), 'op': op, 'at': now().isoformat()}
    if op == 'check': res['login'] = login_check(); push_status(login=res['login'])
    elif op == 'update':
        try:
            req = urllib.request.Request(UPDATE_URL, headers={'User-Agent': 'tkrec/1'}); code = urllib.request.urlopen(req, timeout=60).read()
            tmp = os.path.join(ROOT, 'tkrec.new.py'); open(tmp, 'wb').write(code)
            ok = subprocess.call([sys.executable, '-m', 'py_compile', tmp]) == 0; res['compiled'] = ok
            if ok: os.replace(tmp, os.path.abspath(__file__)); res['updated'] = True
        except Exception as e: res['err'] = str(e)[:200]
    elif op == 'restart': res['restart'] = True
    elif op == 'probe':   # v7: test the quality picker on any live account (no recording)
        u = str(c.get('uid') or UID)
        if re.match(r'^[A-Za-z0-9._]{2,30}$', u):
            url, err = stream_url(u); res['probe'] = {'uid': u, 'ok': bool(url), 'err': err, 'qualities': LAST_Q, 'picked': (LAST_Q[0] if LAST_Q else None)}
        else: res['probe'] = 'bad uid'
    elif op == 'setkey': res.update(set_key(c))
    elif op == 'clip': res['clip'] = start_clip(c.get('slug', ''), c) if re.match(r'^r-\d{6}-\d{4}$', c.get('slug', '')) else 'bad slug'
    elif op == 'autoclip':
        CFG['autoclip'] = bool(c.get('on')); json.dump(CFG, open(os.path.join(HOME, '.tkrec', 'config.json'), 'w')); res['autoclip'] = CFG['autoclip']
    elif op == 'setnotes':
        open(os.path.join(HOME, '.tkrec', 'clipnotes.txt'), 'w').write(str(c.get('text', ''))[:8000]); res['notes'] = len(str(c.get('text', '')))
    elif op == 'stopclips':
        r = subprocess.run(['bash', '-c', "systemctl --user list-units 'clipjob-*' --no-legend --plain | awk '{print $1}' | xargs -r systemctl --user stop; pkill -f 'claude -p'; sleep 1; pgrep -fc 'claude -p'"], capture_output=True, text=True); res['left'] = r.stdout.strip()
    elif op == 'pushclip': push_clip(c.get('slug', '')); res['pushed'] = True
    elif op == 'job': res['job'] = start_job(c)   # v8
    else: res['err'] = 'unknown op'
    kv_put('tkrec:result', json.dumps(res, ensure_ascii=False).encode(), 'application/json')
    if res.get('updated') or res.get('restart'): log('exiting for', op); os._exit(0)   # systemd restarts the service
def main():
    log('tkrec started for @' + UID + ' v8'); push_status(state='idle', chrome=None, login=login_check(), ver=8)
    try: resume_unfinished()
    except Exception: log('resume failed', traceback.format_exc()[-300:])
    last_chrome = 0; last_login = time.time(); last_cmd = 0; done_ids = set()
    while True:
        st, info = room_status()
        if st == 2:
            try: record_live(info)
            except Exception: log('record_live crashed', traceback.format_exc()[-400:]); push_status(state='idle', err='crash')
        else:
            if time.time() - last_chrome > 300:   # heartbeat: is Chrome reachable?
                try:
                    with urllib.request.urlopen('http://127.0.0.1:9222/json/version', timeout=5) as r: push_status(chrome='ok', last_status=st)
                except Exception: push_status(chrome='down', last_status=st)
                last_chrome = time.time()
            if time.time() - last_login > 3600: push_status(login=login_check()); last_login = time.time()   # hourly
            if time.time() - last_cmd > 30:
                last_cmd = time.time(); c = get_cmd()
                if c and c.get('id') and c['id'] not in done_ids: done_ids.add(c['id']); run_cmd(c)
        time.sleep(10)
if __name__ == '__main__':
    if len(sys.argv) > 2 and sys.argv[1] == 'livetest':
        u = sys.argv[2]; url, err = stream_url(u); print('stream', u, 'ok' if url else err)
        if url:
            rc = subprocess.call(['ffmpeg', '-nostdin', '-loglevel', 'error', '-y', '-rw_timeout', '20000000', '-i', url, '-t', '30', '-c', 'copy', ROOT + '/livetest.mp4']); print('ffmpeg rc', rc)
            print(subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration,size', '-of', 'csv=p=0', ROOT + '/livetest.mp4'], capture_output=True, text=True).stdout.strip())
            print('upload', kv_put('livetest/test.mp4', open(ROOT + '/livetest.mp4', 'rb').read(), 'video/mp4'))
        sys.exit()
    if len(sys.argv) > 1 and sys.argv[1] == 'cmdonce':   # run setkey/clip commands now without restarting the recorder
        t0 = time.time(); seen = set()
        while time.time() - t0 < 1800:
            c = get_cmd()
            if c and c.get('id') and c['id'] not in seen and c.get('op') in ('setkey', 'clip', 'pushclip', 'check'):
                seen.add(c['id']); print('cmd', c.get('op'), flush=True); run_cmd(c)
                if c.get('op') == 'clip' and c.get('last', True): print('done', flush=True); break
            time.sleep(5)
        sys.exit()
    if len(sys.argv) > 2 and sys.argv[1] == 'pushclip': push_clip(sys.argv[2]); sys.exit()
    if len(sys.argv) > 2 and sys.argv[1] == 'clipbeat': clip_beat(sys.argv[2]); sys.exit()
    if len(sys.argv) > 1 and sys.argv[1] == 'test':
        print('room:', room_status()); print('stream:', stream_url()); sys.exit()
    main()
