#!/usr/bin/env python3
"""QR12 P1 backfill: CONVERSATIONAL -> OBSERVED for scribe/reextract items."""
import sqlite3, time, sys
from pathlib import Path

ROOT = Path(__file__).parent
DB = ROOT / "Hippocampus" / "pulse_brain.db"

print(f"DB: {DB}")
print("Waiting 5s for daemon activity to settle...")
time.sleep(5)

for attempt in range(10):
    try:
        conn = sqlite3.connect(str(DB), timeout=120, isolation_level=None)
        conn.execute("PRAGMA busy_timeout = 120000")
        conn.execute("PRAGMA journal_mode = WAL")
        conn.execute("PRAGMA synchronous = NORMAL")

        total = 0
        for table in ("lessons", "failures", "patterns"):
            conn.execute("BEGIN")
            cur = conn.execute(f"""
                UPDATE {table} SET source_type='OBSERVED'
                WHERE source_type='CONVERSATIONAL'
                AND (agent LIKE 'scribe:%' OR agent LIKE 'reextract:%'
                     OR agent LIKE 'bridge_claude_llm%')
            """)
            count = cur.rowcount
            conn.execute("COMMIT")
            total += count
            print(f"  {table}: {count} rows updated")

        print(f"Total backfilled: {total}")

        # Verify
        for table in ("lessons", "failures", "patterns"):
            obs = conn.execute(f"SELECT COUNT(*) FROM {table} WHERE source_type='OBSERVED'").fetchone()[0]
            conv = conn.execute(f"SELECT COUNT(*) FROM {table} WHERE source_type='CONVERSATIONAL'").fetchone()[0]
            print(f"  {table}: OBSERVED={obs} CONVERSATIONAL={conv}")

        conn.close()
        print("DONE")
        sys.exit(0)

    except sqlite3.OperationalError as e:
        print(f"Attempt {attempt+1} failed: {e} — waiting 10s...")
        time.sleep(10)

print("All attempts failed — DB too busy. Run again when daemons are idle.")
sys.exit(1)
