"""
DTOs para el dashboard de estadísticas y métricas empresariales
"""

from typing import Dict, List, Optional
from pydantic import BaseModel, Field
from datetime import datetime


class KPIMetric(BaseModel):
    """Métrica individual de KPI"""

    label: str = Field(..., description="Nombre del indicador")
    value: int | float = Field(..., description="Valor actual")
    previous_value: Optional[int | float] = Field(
        None, description="Valor anterior para comparación"
    )
    percentage_change: Optional[float] = Field(None, description="Porcentaje de cambio")
    trend: Optional[str] = Field(None, description="up, down, stable")
    unit: Optional[str] = Field(None, description="Unidad de medida (%, USD, etc)")


class ActivityItem(BaseModel):
    """Item de actividad reciente"""

    id: int
    type: str = Field(
        ..., description="Tipo de actividad: invoice, pedimento, client, etc"
    )
    title: str = Field(..., description="Título descriptivo")
    description: Optional[str] = Field(None, description="Descripción adicional")
    timestamp: datetime
    status: Optional[str] = Field(None, description="Estado del item")
    icon: Optional[str] = Field(None, description="Icono a mostrar")


class ChartDataPoint(BaseModel):
    """Punto de datos para gráficas"""

    label: str
    value: float
    category: Optional[str] = None


class DashboardStats(BaseModel):
    """Estadísticas generales del dashboard"""

    # KPIs principales
    total_invoices: KPIMetric
    total_pedimentos: KPIMetric
    total_clients: KPIMetric
    total_providers: KPIMetric
    active_items: KPIMetric
    pending_approvals: KPIMetric

    # Estadísticas financieras
    total_value_imports: Optional[float] = Field(
        None, description="Valor total de importaciones"
    )
    total_value_exports: Optional[float] = Field(
        None, description="Valor total de exportaciones"
    )

    # Datos para gráficas
    invoices_by_month: List[ChartDataPoint] = Field(default_factory=list)
    pedimentos_by_month: List[ChartDataPoint] = Field(default_factory=list)
    operations_by_type: List[ChartDataPoint] = Field(default_factory=list)
    top_clients: List[ChartDataPoint] = Field(default_factory=list)
    top_providers: List[ChartDataPoint] = Field(default_factory=list)

    # Actividad reciente
    recent_activity: List[ActivityItem] = Field(default_factory=list)

    # Metadata
    generated_at: datetime = Field(default_factory=datetime.utcnow)
    company_id: int
    company_name: Optional[str] = None


class OperationsOverview(BaseModel):
    """Vista general de operaciones"""

    total_operations: int
    by_type: Dict[str, int] = Field(default_factory=dict)
    by_status: Dict[str, int] = Field(default_factory=dict)
    avg_processing_time: Optional[float] = Field(
        None, description="Tiempo promedio en días"
    )


class InventoryMetrics(BaseModel):
    """Métricas de inventario"""

    total_items: int
    items_in_stock: int
    items_low_stock: int
    total_value: Optional[float] = None
    by_category: Dict[str, int] = Field(default_factory=dict)


class ComplianceMetrics(BaseModel):
    """Métricas de cumplimiento normativo"""

    pending_documents: int
    expired_permits: int
    upcoming_deadlines: int
    compliance_score: Optional[float] = Field(
        None, description="Score de cumplimiento 0-100"
    )
