#!/usr/bin/env python3
import json, sqlite3, time, urllib.request
from datetime import datetime, timezone
QID=890
DB='/opt/struktur/youtube-research/knowledge.db'
API='http://127.0.0.1:8644/episodes/inventory'
c=sqlite3.connect(DB); c.row_factory=sqlite3.Row
row=c.execute('select * from graphiti_import_queue where id=?',(QID,)).fetchone()
if not row: raise SystemExit('queue_not_found')
if row['next_attempt_at']:
due=datetime.fromisoformat(row['next_attempt_at'])
delay=(due-datetime.now(timezone.utc)).total_seconds()
if delay>0: time.sleep(delay)
with urllib.request.urlopen(API,timeout=90) as r: episodes=json.loads(r.read()).get('episodes',[])
found=[e for e in episodes if row['import_identity'] in (e.get('source_description') or '')]
now=datetime.now(timezone.utc).isoformat(); attempts=(row['lookup_attempt_count'] or 0)+1
if len(found)==1:
c.execute("update graphiti_import_queue set graphiti_status='done',graphiti_episode_id=?,completed_at=?,remote_outcome='ADOPTED_EXISTING',last_lookup_at=?,lookup_attempt_count=?,lock_owner=NULL,lock_token=NULL,lease_expires_at=NULL,updated_at=? where id=?",(found[0].get('uuid'),now,now,attempts,now,QID)); result={'action':'ADOPTED_EXISTING','uuid':found[0].get('uuid')}
elif len(found)>1:
c.execute("update graphiti_import_queue set graphiti_status='review_required',remote_outcome='AMBIGUOUS',last_lookup_at=?,lookup_attempt_count=?,last_error_class='ambiguous_remote_match',updated_at=? where id=?",(now,attempts,now,QID)); result={'action':'REVIEW_REQUIRED','matches':len(found)}
else:
c.execute("update graphiti_import_queue set remote_outcome='UNKNOWN_REMOTE_OUTCOME',last_lookup_at=?,lookup_attempt_count=?,next_attempt_at=NULL,updated_at=? where id=?",(now,attempts,now,QID)); result={'action':'NO_EPISODE_AFTER_LOOKUP','attempts':attempts}
c.commit(); c.close(); print(json.dumps(result,ensure_ascii=False))