"""Phase 2: Multi-pass Data Overwrite.

Overwrites encrypted content with cryptographic random bytes.
3 passes to ensure no residual data patterns remain.
Follows DOD 5220.22-M inspired approach adapted for SQLite.
"""

import os
import logging
from soagila.db.sqlite_init import get_db

logger = logging.getLogger("soagila.sdijap.data_overwriter")

OVERWRITE_PASSES = 3


async def overwrite_all_data() -> dict:
    """Overwrite all memory data with random bytes, then delete.

    Returns counts of destroyed records per table.
    """
    db = await get_db()
    counts = {
        "episodic": 0,
        "semantic": 0,
        "relationships": 0,
        "topics": 0,
        "canary_tokens": 0,
        "behavioral_profiles": 0,
        "anomaly_events": 0,
    }

    # --- Episodic Memories ---
    cursor = await db.execute("SELECT id FROM episodic_memories")
    ep_ids = [row[0] for row in await cursor.fetchall()]
    counts["episodic"] = len(ep_ids)

    for pass_num in range(1, OVERWRITE_PASSES + 1):
        for mem_id in ep_ids:
            random_content = os.urandom(256)
            await db.execute(
                "UPDATE episodic_memories SET encrypted_content = ?, embedding = NULL, "
                "content_hash = ? WHERE id = ?",
                (random_content, os.urandom(32).hex(), mem_id),
            )
        await db.commit()
        logger.debug(f"Episodic overwrite pass {pass_num}/{OVERWRITE_PASSES} complete")

    await db.execute("DELETE FROM episodic_memories")
    await db.commit()

    # --- Semantic Memories ---
    cursor = await db.execute("SELECT id FROM semantic_memories")
    sem_ids = [row[0] for row in await cursor.fetchall()]
    counts["semantic"] = len(sem_ids)

    for pass_num in range(1, OVERWRITE_PASSES + 1):
        for mem_id in sem_ids:
            random_content = os.urandom(256)
            await db.execute(
                "UPDATE semantic_memories SET encrypted_content = ?, embedding = NULL, "
                "pattern_description = ? WHERE id = ?",
                (random_content, os.urandom(32).hex(), mem_id),
            )
        await db.commit()

    await db.execute("DELETE FROM semantic_memories")
    await db.commit()

    # --- Relationships ---
    cursor = await db.execute("SELECT COUNT(*) FROM memory_relationships")
    counts["relationships"] = (await cursor.fetchone())[0]
    await db.execute("DELETE FROM memory_relationships")

    # --- Topics ---
    cursor = await db.execute("SELECT COUNT(*) FROM memory_topics")
    counts["topics"] = (await cursor.fetchone())[0]
    await db.execute("DELETE FROM memory_topics")
    await db.execute("DELETE FROM topics")

    # --- Canary Tokens ---
    cursor = await db.execute("SELECT COUNT(*) FROM canary_tokens")
    counts["canary_tokens"] = (await cursor.fetchone())[0]
    await db.execute("DELETE FROM canary_tokens")

    # --- Behavioral Profiles ---
    cursor = await db.execute("SELECT COUNT(*) FROM behavioral_profiles")
    counts["behavioral_profiles"] = (await cursor.fetchone())[0]
    await db.execute("DELETE FROM behavioral_profiles")

    # --- Anomaly Events ---
    cursor = await db.execute("SELECT COUNT(*) FROM anomaly_events")
    counts["anomaly_events"] = (await cursor.fetchone())[0]
    await db.execute("DELETE FROM anomaly_events")

    # --- Annihilation Requests (mark as completed, don't delete) ---
    # These are kept as proof of destruction

    await db.commit()

    # NOTE: decision_receipts are NOT deleted — they serve as the audit trail
    # The final annihilation receipt will be the last entry in the chain

    logger.info(
        f"Phase 2 complete: {counts['episodic']} episodic, {counts['semantic']} semantic, "
        f"{counts['relationships']} relationships destroyed ({OVERWRITE_PASSES} passes)"
    )
    return counts
