"""SDIJAP Annihilator — Orchestrates 3-phase cryptographic data destruction.

Phase 1: Key Destruction — all encryption keys permanently destroyed
Phase 2: Data Overwrite — 3 passes of random bytes over all memory data
Phase 3: Embedding Poisoning — vector residue replaced with noise

After all 3 phases, SQLite VACUUM reclaims space and eliminates WAL traces.
A final Annihilation Receipt is created as cryptographic proof of destruction.
"""

import time
import logging
from datetime import datetime, timezone

from soagila.core.sdijap.models import AnnihilationResult
from soagila.core.sdijap.key_destroyer import destroy_all_keys
from soagila.core.sdijap.data_overwriter import overwrite_all_data
from soagila.core.sdijap.embedding_poisoner import poison_all_embeddings
from soagila.db.sqlite_init import get_db
from soagila.db.event_bus import publish_event

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

CHANNEL = "soagila:metrics"


async def annihilate(scope: str = "project") -> AnnihilationResult:
    """Execute full SDIJAP annihilation protocol.

    Args:
        scope: "project" = current project only, "all" = all SOAGILA data

    Returns:
        AnnihilationResult with counts and proof
    """
    start = time.monotonic()
    result = AnnihilationResult(scope=scope, status="executing")

    logger.warning(f"SDIJAP ANNIHILATION INITIATED — scope={scope}")
    logger.warning("This is IRREVERSIBLE. All memory data will be destroyed.")

    # ═══ Phase 3 FIRST: Poison embeddings before deletion ═══
    # (Must run before Phase 2 deletes the rows)
    logger.info("Phase 3: Embedding poisoning...")
    result.embeddings_poisoned = await poison_all_embeddings()

    # ═══ Phase 1: Key Destruction ═══
    logger.info("Phase 1: Key destruction...")
    result.keys_destroyed, result.key_refs_destroyed = await destroy_all_keys()

    # ═══ Phase 2: Data Overwrite ═══
    logger.info("Phase 2: Data overwrite (3 passes)...")
    counts = await overwrite_all_data()
    result.episodic_destroyed = counts["episodic"]
    result.semantic_destroyed = counts["semantic"]
    result.relationships_destroyed = counts["relationships"]
    result.topics_destroyed = counts["topics"]
    result.overwrite_passes = 3

    # ═══ VACUUM: Reclaim space, eliminate WAL traces ═══
    logger.info("Running SQLite VACUUM...")
    db = await get_db()
    await db.execute("VACUUM")

    # Count remaining receipts (preserved for audit)
    cursor = await db.execute("SELECT COUNT(*) FROM decision_receipts")
    result.receipts_preserved = (await cursor.fetchone())[0]

    # ═══ Create Annihilation Receipt ═══
    # This is the FINAL entry in the Merkle chain — proof of destruction
    from soagila.core.idl.ledger import create_receipt
    import json

    receipt = await create_receipt(
        receipt_type="annihilate",
        user_id="local",
        metadata={
            "scope": scope,
            "method": "SDIJAP-v1",
            "phases": 3,
            "keys_destroyed": result.keys_destroyed,
            "episodic_destroyed": result.episodic_destroyed,
            "semantic_destroyed": result.semantic_destroyed,
            "embeddings_poisoned": result.embeddings_poisoned,
            "relationships_destroyed": result.relationships_destroyed,
            "overwrite_passes": result.overwrite_passes,
        },
    )
    result.receipt_id = receipt.id

    # Timing
    elapsed_ms = (time.monotonic() - start) * 1000
    result.duration_ms = round(elapsed_ms, 2)
    result.timestamp = datetime.now(timezone.utc).isoformat()
    result.status = "completed"

    # Publish annihilation event
    event = json.dumps({
        "type": "annihilation_complete",
        "scope": scope,
        "receipt_id": receipt.id,
        "keys_destroyed": result.keys_destroyed,
        "memories_destroyed": result.episodic_destroyed + result.semantic_destroyed,
        "embeddings_poisoned": result.embeddings_poisoned,
        "duration_ms": result.duration_ms,
        "timestamp": result.timestamp,
    })
    await publish_event(CHANNEL, event)

    logger.warning(
        f"SDIJAP ANNIHILATION COMPLETE — "
        f"{result.keys_destroyed} keys, "
        f"{result.episodic_destroyed} episodic, "
        f"{result.semantic_destroyed} semantic, "
        f"{result.embeddings_poisoned} embeddings, "
        f"receipt={receipt.id[:8]}... "
        f"({result.duration_ms}ms)"
    )

    return result
