#!/usr/bin/env python3
"""Opt-in SignalDesk metadata bridge. Requires Python 3.10+. No third-party packages.
Run with SIGNALDESK_TOKEN set to a Codex connection token from your workspace.
Only local root task names/timestamps are sent. No prompts, transcripts or cwd paths.
Stops sending when the token expires or is revoked. Ctrl-C stops observation.
"""
import os,json,sqlite3,time,hashlib,urllib.request,urllib.error,pathlib
ENDPOINT='https://signaldesk.barichholdings.com/api/ingest'
def observations(database):
    with sqlite3.connect('file:'+str(database)+'?mode=ro',uri=True,timeout=2) as db:
        rows=db.execute("SELECT id,COALESCE(NULLIF(name,''),NULLIF(title,''),'Untitled task'),updated_at FROM threads WHERE archived=0 AND agent_path IS NULL AND source='vscode' ORDER BY updated_at DESC LIMIT 100").fetchall()
    for identity,title,updated in rows:
        # Preserve only user-visible names. Raw referenced-history placeholders are omitted.
        if title.startswith('## Referenced ChatGPT conversation') or title.startswith('The following is the Codex agent history'):continue
        yield {'externalId':hashlib.sha256((identity+':'+str(updated)).encode()).hexdigest(),'title':title[:500],'url':'','state':'observed','observedAt':int(updated*1000)}
def main():
    token=os.environ.get('SIGNALDESK_TOKEN','');database=pathlib.Path.home()/'.codex/state_5.sqlite'
    if len(token)!=64 or any(c not in '0123456789abcdef' for c in token):raise SystemExit('Set SIGNALDESK_TOKEN to your workspace Codex connection token. Never paste it into a chat or source file.')
    print('SignalDesk bridge enabled. Sends local task titles and timestamps; no messages or workspace paths. Ctrl-C stops.')
    sent=set();backoff=60
    while True:
        try:
            for event in observations(database):
                if event['observedAt']<int((time.time()-90*86400)*1000):continue
                if event['externalId'] in sent:continue
                request=urllib.request.Request(ENDPOINT,data=json.dumps(event).encode(),headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'},method='POST')
                with urllib.request.urlopen(request,timeout=15) as response:
                    if response.status!=200:raise RuntimeError('Unexpected response')
                sent.add(event['externalId'])
            backoff=60
        except urllib.error.HTTPError as error:
            if error.code in (401,403):raise SystemExit('Connection rejected. Create a new workspace token before restarting.')
            print('Delivery unavailable, HTTP',error.code,'; retrying later.');backoff=min(backoff*2,1800)
        except (OSError,sqlite3.Error,RuntimeError):
            print('Source or network unavailable; retrying without modifying Codex.');backoff=min(backoff*2,1800)
        time.sleep(backoff)
if __name__=='__main__':
    try:main()
    except KeyboardInterrupt:print('\nSignalDesk bridge stopped.')
