#!/usr/bin/env python3
"""
Fix cross-table contradictions: items existing as both LESSON and FAILURE.

Strategy: Keep the failure (learning from mistakes > celebrating success),
delete the lesson duplicate, merge evidence counts.

Run: python -m pulse.admin.brain_ops.fix_contradictions
"""
import sqlite3
import os
import time


def fix_contradictions(db_path: str = None, max_retries: int = 10) -> dict:
    if db_path is None:
        db_path = os.path.join("Hippocampus", "pulse_brain.db")

    for attempt in range(max_retries):
        try:
            conn = sqlite3.connect(db_path, timeout=60, isolation_level="DEFERRED")
            conn.row_factory = sqlite3.Row
            conn.execute("PRAGMA busy_timeout = 60000")
            conn.execute("PRAGMA journal_mode = WAL")

            dupes = conn.execute("""
                SELECT l.id as lesson_id, f.id as failure_id, l.title,
                       l.confidence as l_conf, f.confidence as f_conf,
                       COALESCE(l.evidence_count,1) as l_ev,
                       COALESCE(f.evidence_count,1) as f_ev
                FROM lessons l
                JOIN failures f ON l.title = f.title
                WHERE l.title IS NOT NULL AND l.title != ''
            """).fetchall()

            if not dupes:
                conn.close()
                return {"fixed": 0, "message": "No contradictions found"}

            fixed = 0
            for d in dupes:
                lesson_id = d["lesson_id"]
                failure_id = d["failure_id"]
                l_conf, f_conf = d["l_conf"], d["f_conf"]
                l_ev, f_ev = d["l_ev"], d["f_ev"]

                # Merge evidence: keep higher count
                if l_ev > f_ev:
                    conn.execute(
                        "UPDATE failures SET evidence_count = ? WHERE id = ?",
                        (l_ev, failure_id),
                    )
                # Merge confidence: boost failure if lesson was higher
                if l_conf > f_conf:
                    new_conf = min(1.0, f_conf + (l_conf - f_conf) * 0.5)
                    conn.execute(
                        "UPDATE failures SET confidence = ? WHERE id = ?",
                        (round(new_conf, 4), failure_id),
                    )
                # Delete the lesson duplicate
                conn.execute("DELETE FROM lessons WHERE id = ?", (lesson_id,))
                fixed += 1

            conn.commit()
            conn.close()
            return {"fixed": fixed, "message": f"Deleted {fixed} contradictory lessons"}

        except sqlite3.OperationalError as e:
            if "locked" in str(e).lower() and attempt < max_retries - 1:
                time.sleep(3)
                continue
            raise

    return {"fixed": 0, "message": "DB locked after all retries"}


if __name__ == "__main__":
    result = fix_contradictions()
    print(result["message"])
