#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Item 122: Catastrophic forgetting protection (Memory — P29).

When a new item shares a fingerprint with a high-confidence existing item
(confidence > 0.8), keep BOTH versions instead of silently ignoring the new one.
Models synaptic consolidation: strongly-encoded memories resist overwriting.

Extracted into its own module to keep brain_db.py under 300 lines.
"""
import hashlib
import logging
from typing import Tuple

log = logging.getLogger("pulse.forgetting_protection")

HIGH_CONFIDENCE_THRESHOLD = 0.8  # Items above this resist overwriting


def protect_high_confidence(
    conn, table: str, fingerprint: str, item_id: str, ts: str
) -> Tuple[str, str]:
    """Check if existing item with same fingerprint has confidence > 0.8.

    If so, return a new (item_id, fingerprint) pair so both versions survive.
    Otherwise return the original (item_id, fingerprint) unchanged.

    Args:
        conn: SQLite connection (with row_factory = sqlite3.Row)
        table: Table name to check (e.g. 'lessons')
        fingerprint: Fingerprint of the incoming item
        item_id: Proposed ID for the incoming item
        ts: Timestamp of the incoming item (used to generate unique ID)

    Returns:
        (item_id, fingerprint) — possibly modified to prevent overwrite
    """
    try:
        existing_row = conn.execute(
            f"SELECT id, confidence FROM {table} WHERE fingerprint = ?",
            (fingerprint,)
        ).fetchone()
        if existing_row and float(existing_row["confidence"] or 0) > HIGH_CONFIDENCE_THRESHOLD:
            # High-confidence item exists — generate a distinct ID and fingerprint
            # so INSERT OR IGNORE will insert a new row instead of skipping
            suffix = hashlib.md5((fingerprint + ts).encode("utf-8")).hexdigest()[:12]
            new_item_id = f"L-v2-{suffix}"
            new_fingerprint = fingerprint + "-v2"
            log.debug(
                "Catastrophic forgetting protection: high-conf item %s (conf=%.2f) "
                "will coexist with new item %s",
                existing_row["id"],
                float(existing_row["confidence"] or 0),
                new_item_id,
            )
            return new_item_id, new_fingerprint
    except Exception as e:
        log.debug("protect_high_confidence failed: %s", e)
    return item_id, fingerprint  # fail-open: return originals
