"""Pydantic models for IA API communication.

Copyright 2026 Maggioli SPA
Licensed under Apache 2.0
Author: Costas Vrioni (costas.vrioni@maggioli.gr)

This module provides data models for communication with the XAI Suite
IA Service API, supporting both v1 and v2 API versions.
"""

from datetime import datetime
from typing import Any, Optional

from pydantic import BaseModel, Field


# =============================================================================
# V1 API Models
# =============================================================================

class ExplanationRequest(BaseModel):
    """Request model for narrative generation (v1 API)."""

    method: str = Field(..., description="The explanation method used (e.g., 'SHAP', 'LIME')")
    feature_names: list[str] = Field(..., description="Names of the features in the explanation")
    importance_scores: list[float] = Field(..., description="Feature importance scores")
    feature_values: Optional[list[float]] = Field(
        None, description="Actual feature values for the instance"
    )
    base_value: Optional[float] = Field(None, description="Base value for SHAP explanations")
    output_value: Optional[float] = Field(None, description="Model output value")
    model_type: Optional[str] = Field(
        None, description="Type of model (e.g., 'classification', 'anomaly_detection')"
    )
    context: Optional[dict[str, Any]] = Field(
        None, description="Additional context for narrative generation"
    )


class NarrativeResponse(BaseModel):
    """Response model from narrative generation (v1 API)."""

    narrative: str = Field(..., description="Human-readable narrative explanation")
    compliance_id: str = Field(..., description="Audit ID for EU AI Act compliance")
    timestamp: datetime = Field(..., description="Timestamp of narrative generation")
    method: str = Field(..., description="The explanation method that was processed")


class HealthResponse(BaseModel):
    """Health check response model."""

    status: str = Field(..., description="Service status")
    version: str = Field(..., description="Service version")
    timestamp: datetime = Field(..., description="Current server time")
    llm_backend: Optional[str] = Field(None, description="LLM backend in use")
    available_domains: list[str] = Field(default_factory=list, description="Available domain contexts")


class ErrorResponse(BaseModel):
    """Error response model."""

    error: str = Field(..., description="Error type")
    message: str = Field(..., description="Error message")
    timestamp: datetime = Field(..., description="Error timestamp")


# =============================================================================
# V2 API Models
# =============================================================================

class ExplanationRequestV2(BaseModel):
    """Request model for v2 API with enhanced features."""

    method: str = Field(..., description="The explanation method used (SHAP, LIME)")
    feature_names: list[str] = Field(..., description="Names of the features")
    importance_scores: list[float] = Field(..., description="Feature importance scores")
    feature_values: Optional[list[float]] = Field(None, description="Actual feature values")
    base_value: Optional[float] = Field(None, description="Base value for SHAP")
    output_value: Optional[float] = Field(None, description="Model output/prediction value")
    model_type: Optional[str] = Field(
        None,
        description="Type of model (classification, anomaly_detection, regression)"
    )
    domain: Optional[str] = Field(
        "generic",
        description="Domain context (generic, cybersecurity, etc.)"
    )
    domain_context: Optional[dict[str, Any]] = Field(
        None,
        description="Additional domain-specific context"
    )
    include_insights: bool = Field(
        True,
        description="Whether to generate actionable insights"
    )
    include_compliance: bool = Field(
        True,
        description="Whether to include EU AI Act compliance references"
    )


class Insight(BaseModel):
    """A single actionable insight from the explanation analysis."""

    type: str = Field(..., description="Type of insight (warning, recommendation, observation)")
    priority: str = Field(..., description="Priority level (critical, high, medium, low)")
    title: str = Field(..., description="Short title for the insight")
    description: str = Field(..., description="Detailed description")
    action: Optional[str] = Field(None, description="Recommended action to take")
    related_features: list[str] = Field(
        default_factory=list,
        description="List of feature names related to this insight"
    )


class ApplicableArticle(BaseModel):
    """Summary of an applicable EU AI Act article."""

    article: str = Field(..., description="Article identifier (e.g., 'article_13')")
    title: str = Field(..., description="Article title")
    relevance: str = Field(..., description="How this article relates to the explanation")


class ComplianceResponse(BaseModel):
    """Compliance information from the v2 API."""

    audit_id: str = Field(..., description="Unique audit identifier for this request")
    timestamp: datetime = Field(..., description="When this explanation was generated")
    applicable_articles: list[ApplicableArticle] = Field(
        default_factory=list,
        description="EU AI Act articles applicable to this explanation"
    )


class NarrativeResponseV2(BaseModel):
    """Narrative section of the v2 API response."""

    text: str = Field(..., description="Generated narrative text")
    method: str = Field(..., description="Explanation method processed")
    domain: str = Field(..., description="Domain context used")
    timestamp: datetime = Field(..., description="Generation timestamp")


class ExplanationResponseV2(BaseModel):
    """Complete response model for v2 API."""

    narrative: NarrativeResponseV2 = Field(..., description="Generated narrative")
    insights: list[Insight] = Field(
        default_factory=list,
        description="Actionable insights derived from the explanation"
    )
    compliance: ComplianceResponse = Field(
        ...,
        description="EU AI Act compliance information"
    )


class DomainInfo(BaseModel):
    """Information about an available domain."""

    id: str = Field(..., description="Domain identifier")
    name: str = Field(..., description="Human-readable domain name")
    description: str = Field(..., description="Domain description")


class DomainsResponse(BaseModel):
    """Response for listing available domains."""

    domains: list[DomainInfo] = Field(..., description="List of available domains")
