"""SOAGILA Compliance Reports — Auto-generated from IDL receipts.

Enterprise feature: generates audit reports from the Immutable Decision Ledger.
Supports GDPR, HIPAA, SOX, EU AI Act compliance frameworks.
"""

import json
import logging
from datetime import datetime, timezone

from soagila.db.sqlite_init import get_db
from soagila.core.idl.ledger import verify_chain, get_chain_length

logger = logging.getLogger("soagila.compliance")


async def generate_report(
    framework: str = "general",
    days: int = 30,
) -> dict:
    """Generate a compliance report from IDL decision receipts.

    Args:
        framework: "general", "gdpr", "hipaa", "sox", "eu_ai_act"
        days: Number of days to cover

    Returns:
        Structured compliance report dict
    """
    from soagila.project_manager import is_feature_allowed
    allowed, msg = is_feature_allowed("compliance")
    if not allowed:
        return {"error": msg, "status": "denied"}

    db = await get_db()
    cutoff = datetime.now(timezone.utc)
    from datetime import timedelta
    cutoff_str = (cutoff - timedelta(days=days)).isoformat()

    # Gather statistics from receipts
    cursor = await db.execute(
        "SELECT COUNT(*) FROM decision_receipts WHERE created_at >= ?",
        (cutoff_str,),
    )
    total_receipts = (await cursor.fetchone())[0]

    # Receipts by type
    cursor = await db.execute(
        """SELECT receipt_type, COUNT(*) as cnt
           FROM decision_receipts WHERE created_at >= ?
           GROUP BY receipt_type ORDER BY cnt DESC""",
        (cutoff_str,),
    )
    type_counts = {row[0]: row[1] for row in await cursor.fetchall()}

    # Memory statistics
    cursor = await db.execute("SELECT COUNT(*) FROM episodic_memories WHERE is_decayed = 0")
    active_memories = (await cursor.fetchone())[0]

    cursor = await db.execute("SELECT COUNT(*) FROM episodic_memories WHERE is_decayed = 1")
    decayed_memories = (await cursor.fetchone())[0]

    cursor = await db.execute("SELECT COUNT(*) FROM semantic_memories")
    semantic_count = (await cursor.fetchone())[0]

    # Annihilation history
    cursor = await db.execute(
        "SELECT COUNT(*) FROM decision_receipts WHERE receipt_type = 'annihilate'"
    )
    annihilation_count = (await cursor.fetchone())[0]

    # Chain integrity
    chain = await verify_chain()

    # PII detection stats (from receipts metadata)
    cursor = await db.execute(
        """SELECT COUNT(*) FROM decision_receipts
           WHERE receipt_type = 'store' AND created_at >= ?""",
        (cutoff_str,),
    )
    store_ops = (await cursor.fetchone())[0]

    # Build report
    report = {
        "report_type": "compliance",
        "framework": framework,
        "period_days": days,
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "summary": {
            "total_operations": total_receipts,
            "operations_by_type": type_counts,
            "active_memories": active_memories,
            "decayed_memories": decayed_memories,
            "semantic_patterns": semantic_count,
            "data_annihilations": annihilation_count,
        },
        "chain_integrity": {
            "merkle_chain_length": get_chain_length(),
            "chain_valid": chain["valid"],
            "message": chain.get("message", ""),
        },
        "security": {
            "encryption": "AES-256-GCM",
            "pii_detection": "Active (13 pattern types)",
            "behavioral_monitoring": "BAS 0-100 scoring",
            "canary_tokens": "Active",
        },
    }

    # Framework-specific sections
    if framework == "gdpr":
        report["gdpr"] = {
            "data_minimization": f"Ebbinghaus decay active. {decayed_memories} memories naturally expired.",
            "right_to_erasure": f"SDIJAP annihilation available. {annihilation_count} executions recorded.",
            "data_portability": "All data stored locally in user-controlled SQLite.",
            "consent": "User explicitly installs extension and configures settings.",
            "encryption_at_rest": "AES-256-GCM for all stored memories.",
            "audit_trail": f"Merkle-chained decision ledger with {get_chain_length()} receipts.",
        }
    elif framework == "hipaa":
        report["hipaa"] = {
            "phi_protection": "PII detection with 13 pattern types. All content encrypted.",
            "access_controls": "Single-user local deployment. BAS monitoring.",
            "audit_controls": f"Complete audit trail: {total_receipts} receipts.",
            "data_integrity": f"Merkle chain integrity: {'VALID' if chain['valid'] else 'BROKEN'}.",
        }
    elif framework == "eu_ai_act":
        report["eu_ai_act"] = {
            "explainability": "Every AI decision traced via Decision Receipts. Backward/forward trace available.",
            "human_oversight": "All memory operations logged and auditable.",
            "data_governance": "PII detection, encryption, decay, and annihilation protocols.",
            "risk_management": "Behavioral Anomaly Scoring (BAS) + Canary Token detection.",
        }

    logger.info(f"Compliance report generated: {framework}, {days} days, {total_receipts} operations")
    return report
