"""
AgentGuard Configuration

EU AI Act risk classification and compliance settings.
Reference: Regulation (EU) 2024/1689
"""

from __future__ import annotations

from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Callable

from pydantic import BaseModel, Field


class RiskLevel(str, Enum):
    """EU AI Act risk classification (Articles 5-7, Annex III)."""

    MINIMAL = "minimal"
    LIMITED = "limited"  # Transparency obligations (Article 50)
    HIGH = "high"  # Full compliance (Articles 8-15)


class AuditBackend(str, Enum):
    """Where to store audit logs."""

    FILE = "file"  # JSON lines file (default)
    SQLITE = "sqlite"  # SQLite database
    CUSTOM = "custom"  # User-provided callback


class DisclosureMethod(str, Enum):
    """How to disclose AI interaction to users."""

    PREPEND = "prepend"  # Add disclosure text before response
    METADATA = "metadata"  # Add to response metadata
    HEADER = "header"  # HTTP header (for API deployments)
    CALLBACK = "callback"  # Custom callback function


class HumanEscalation(str, Enum):
    """When to route to human oversight."""

    NEVER = "never"  # No automatic escalation
    LOW_CONFIDENCE = "low_confidence"  # When model signals uncertainty
    SENSITIVE_TOPIC = "sensitive_topic"  # Keyword/topic detection
    ALWAYS_REVIEW = "always_review"  # Queue all for human review


class ContentLabel(BaseModel):
    """Metadata label for AI-generated content (Article 50(2))."""

    generator: str  # System that generated the content
    model: str | None = None  # Underlying model if known
    timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
    provider: str  # Organization deploying the system
    ai_generated: bool = True
    interaction_id: str | None = None


class AgentGuardConfig(BaseModel):
    """Main configuration for AgentGuard compliance middleware."""

    # --- Identity (Article 16) ---
    system_name: str = Field(..., description="Name of the AI system being deployed")
    provider_name: str = Field(..., description="Legal name of the organization deploying the AI")
    version: str = Field(default="0.1.0", description="Version of the AI system")

    # --- Risk Classification (Articles 5-7) ---
    risk_level: RiskLevel = Field(
        default=RiskLevel.LIMITED,
        description="EU AI Act risk classification of this system",
    )
    intended_purpose: str = Field(
        default="",
        description="Description of the system's intended purpose (Article 13)",
    )

    # --- Transparency (Article 50) ---
    disclosure_method: DisclosureMethod = Field(default=DisclosureMethod.PREPEND)
    disclosure_text: str = Field(
        default="🤖 This response was generated by an AI system ({system_name}) "
        "operated by {provider_name}.",
        description="Disclosure template. Supports {system_name} and {provider_name} placeholders.",
    )
    label_content: bool = Field(
        default=True,
        description="Add machine-readable labels to AI-generated content (Article 50(2))",
    )

    # --- Audit & Logging (Article 12) ---
    audit_backend: AuditBackend = Field(default=AuditBackend.FILE)
    audit_path: Path = Field(
        default=Path("./agentguard_audit"),
        description="Directory for audit logs",
    )
    log_inputs: bool = Field(default=True, description="Log user inputs (ensure GDPR compliance)")
    log_outputs: bool = Field(default=True, description="Log AI outputs")
    retention_days: int = Field(
        default=365,
        description="How long to retain audit logs (days)",
    )

    # --- Human Oversight (Article 14) ---
    human_escalation: HumanEscalation = Field(default=HumanEscalation.LOW_CONFIDENCE)
    confidence_threshold: float = Field(
        default=0.7,
        description="Below this confidence, escalate to human (0.0-1.0)",
    )
    sensitive_keywords: list[str] = Field(
        default_factory=lambda: [
            "legal",
            "medical",
            "financial advice",
            "diagnosis",
            "terminate",
            "fire",
            "lawsuit",
            "suicide",
            "emergency",
        ],
        description="Keywords that trigger human escalation",
    )
    escalation_callback: Callable | None = Field(
        default=None, description="Function to call when escalating to human"
    )

    # --- High-Risk Specific (Articles 9-15) ---
    risk_management_ref: str | None = Field(
        default=None,
        description="Reference to risk management system documentation (Article 9)",
    )
    data_governance_ref: str | None = Field(
        default=None,
        description="Reference to data governance documentation (Article 10)",
    )
    technical_doc_ref: str | None = Field(
        default=None,
        description="Reference to technical documentation (Article 11)",
    )

    model_config = {"arbitrary_types_allowed": True}

    def render_disclosure(self) -> str:
        """Render disclosure text with placeholders filled."""
        return self.disclosure_text.format(
            system_name=self.system_name,
            provider_name=self.provider_name,
        )
