import gc
import logging
from pydantic import BaseModel

from soagila.core.airlock.pii_detector import detect_pii, PIIDetectionResult
from soagila.core.airlock.classifier import classify_content, assess_importance
from soagila.core.airlock.key_manager import get_or_create_user_mek
from soagila.core.encryption.simulated_he import get_encryption_engine

logger = logging.getLogger("soagila.airlock.pipeline")


class AirlockResult(BaseModel):
    encrypted_content: bytes
    encryption_key_ref: str
    pii_detected: PIIDetectionResult
    classification: str
    importance: float
    tier_recommendation: str  # working / episodic
    plaintext_destroyed: bool = True


async def process(
    content: str,
    user_id: str,
    org_id: str,
) -> AirlockResult:
    """
    Cryptographic Airlock Pipeline:
    1. PII Detection
    2. Content Classification
    3. Importance Assessment
    4. Tier Recommendation
    5. Encryption (AES-256-GCM)
    6. Plaintext Destruction

    Data enters plaintext, exits encrypted. One-way passage.
    """
    # Step 1: PII Detection
    pii_result = detect_pii(content)

    # Step 2: Classification
    classification = classify_content(content)

    # Step 3: Importance Assessment
    importance = assess_importance(content, classification, pii_result.pii_found)

    # Step 4: Tier Recommendation
    tier = "episodic"  # default to episodic for persistence
    if importance < 0.3:
        tier = "working"  # low importance stays ephemeral

    # Step 5: Encryption
    engine = get_encryption_engine()
    key_ref = get_or_create_user_mek(user_id)
    encrypted_content = engine.encrypt(content, key_ref)

    # Step 6: Plaintext Destruction
    # Overwrite the local variable with zeros, then delete
    content_len = len(content)
    content = "\x00" * content_len  # overwrite in memory
    del content
    gc.collect()  # encourage garbage collection

    result = AirlockResult(
        encrypted_content=encrypted_content,
        encryption_key_ref=key_ref,
        pii_detected=pii_result,
        classification=classification,
        importance=importance,
        tier_recommendation=tier,
        plaintext_destroyed=True,
    )

    logger.debug(
        f"Airlock processed: classification={classification}, "
        f"importance={importance:.2f}, pii={pii_result.pii_types}, "
        f"tier={tier}, encrypted=True"
    )

    return result


def decrypt_content(encrypted_content: bytes, key_ref: str) -> str:
    """Decrypt content through the airlock (reverse direction, logged)."""
    engine = get_encryption_engine()
    return engine.decrypt(encrypted_content, key_ref)
