from pydantic import BaseModel, Field
from datetime import datetime
from uuid import uuid4
from typing import Any


class AccessEvent(BaseModel):
    """Represents a single user access event for behavioral analysis."""
    user_id: str
    session_id: str | None = None
    event_type: str = "api_call"  # api_call / login / query / store / export
    endpoint: str = ""
    topic: str = ""
    timestamp: datetime = Field(default_factory=datetime.utcnow)
    metadata: dict[str, Any] = {}


class BehavioralProfileModel(BaseModel):
    """User behavioral baseline."""
    user_id: str
    avg_session_duration_minutes: float = 30.0
    typical_work_hours: dict[str, str] = {"start": "09:00", "end": "18:00"}
    avg_queries_per_session: float = 10.0
    common_topics: list[str] = []
    avg_events_per_hour: float = 5.0
    total_events: int = 0
    baseline_updated_at: datetime = Field(default_factory=datetime.utcnow)


class AnomalyEventModel(BaseModel):
    """Detected anomaly event."""
    id: str = Field(default_factory=lambda: str(uuid4()))
    user_id: str
    session_id: str | None = None
    bas_score: float
    anomaly_type: str  # unusual_hour / unusual_frequency / unusual_access_pattern / unusual_topic / geo_anomaly
    details: dict[str, Any] = {}
    action_taken: str = "logged"  # logged / enhanced_monitoring / session_restricted / mfa_required / frozen
    resolved: bool = False
    created_at: datetime = Field(default_factory=datetime.utcnow)
