#!/usr/bin/env python3
"""Example Stop-hook adapter: current assistant message -> bounded local queue.
No transcript reads, model calls, shell execution, or network requests.
"""
import argparse, hashlib, json, re, sqlite3, sys, time
from pathlib import Path

MARKER = re.compile(r'^\s*(?:🗣|📢|🎙|🎤)\ufe0f?\s*([a-zA-Z][a-zA-Z0-9_-]{0,31}):\s*(.+?)\s*$')

def connect(state):
    state.mkdir(parents=True, exist_ok=True, mode=0o700)
    db = sqlite3.connect(state / 'queue.sqlite3', timeout=1)
    db.execute('CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY, voice TEXT, text TEXT, created REAL, status TEXT)')
    db.commit()
    return db

def choose(message, voices):
    fence = None
    for line in message.splitlines():
        stripped = line.lstrip()
        if stripped.startswith(('```', '~~~')):
            marker = stripped[:3]
            if fence is None: fence = marker
            elif marker == fence: fence = None
            continue
        if fence: continue
        match = MARKER.fullmatch(line)
        if match:
            role, text = match.groups(); role = role.lower()
            if role not in voices: continue
            text = re.sub(r'[\x00-\x1f\x7f]', '', text).strip()
            if text and len(text) <= 450: return role, text
    return None

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', type=Path, default=Path(__file__).with_name('config.json'))
    args = parser.parse_args()
    try:
        cfg = json.loads(args.config.read_text(encoding='utf-8'))
        event = json.loads(sys.stdin.buffer.read(1048577))
        if cfg.get('mute', False) or event.get('hook_event_name') != 'Stop' or event.get('stop_hook_active'): return
        message = event.get('last_assistant_message')
        if not isinstance(message, str): return  # Never guess by searching old transcripts.
        item = choose(message, cfg['voices'])
        if not item: return
        role, text = item
        # Identical summaries deduplicate per session (or per turn, when provided).
        identity = [str(event.get('session_id', '')), str(event.get('turn_id', '')), role, text]
        job_id = hashlib.sha256(json.dumps(identity).encode()).hexdigest()
        state = Path(cfg['state_dir']).expanduser().resolve()
        db = connect(state)
        with db:
            db.execute('BEGIN IMMEDIATE')
            db.execute('DELETE FROM jobs WHERE created < ?', (time.time()-604800,))
            db.execute("UPDATE jobs SET status='expired', text=NULL WHERE status='queued' AND created < ?", (time.time()-300,))
            count = db.execute("SELECT count(*) FROM jobs WHERE status='queued'").fetchone()[0]
            if count < 20:
                db.execute('INSERT OR IGNORE INTO jobs VALUES (?,?,?,?,?)', (job_id, role, text, time.time(), 'queued'))
        db.close()
    except Exception as exc:
        # No raw prompt/text in errors; optional speech must not request another turn.
        print('Narration skipped: ' + type(exc).__name__, file=sys.stderr)

if __name__ == '__main__':
    main()
    print('{}')  # Valid informational Stop-hook output; never blocks or continues.
