"""Phase 1: Cryptographic Key Destruction.

Destroys all encryption keys, making encrypted data permanently unreadable.
Even if the ciphertext survives, it is computationally equivalent to random noise.
"""

import logging
from soagila.core.encryption.simulated_he import get_encryption_engine
from soagila.db.sqlite_init import get_db

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


async def destroy_all_keys() -> tuple[int, list[str]]:
    """Destroy all encryption keys in memory and SQLite.

    Returns (count_destroyed, list_of_key_refs).
    """
    engine = get_encryption_engine()
    destroyed_refs = []

    # Get all key refs from the engine's in-memory store
    key_refs = list(engine._key_store.keys())

    for key_ref in key_refs:
        try:
            engine.destroy_key(key_ref)
            destroyed_refs.append(key_ref)
        except Exception as e:
            logger.error(f"Failed to destroy key {key_ref}: {e}")

    # Also destroy any persisted keys in SQLite
    db = await get_db()
    cursor = await db.execute("SELECT key_ref FROM encryption_keys")
    rows = await cursor.fetchall()

    for row in rows:
        ref = row[0]
        if ref not in destroyed_refs:
            destroyed_refs.append(ref)

    # Delete all persisted keys
    await db.execute("DELETE FROM encryption_keys")
    await db.commit()

    count = len(destroyed_refs)
    logger.info(f"Phase 1 complete: {count} encryption keys destroyed")
    return count, destroyed_refs
