from __future__ import annotations

from typing import Optional

from pydantic import BaseModel, ConfigDict, Field

from .enums import RiskLevel, RiskPrimitive


class PrimitiveScore(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    primitive: RiskPrimitive
    score: int = Field(ge=0, le=10)
    reasons: list[str] = Field(default_factory=list)


class ChainDetection(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    chain_id: str = Field(alias="chainId")
    name: str
    matched_steps: list[str] = Field(default_factory=list, alias="matchedSteps")
    score_boost: int = Field(default=0, alias="scoreBoost")


class CheckResult(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    allow: bool
    score: int = Field(ge=0, le=10)
    level: RiskLevel
    primitive: RiskPrimitive | None = None
    primitive_scores: list[PrimitiveScore] = Field(default_factory=list, alias="primitiveScores")
    reasons: list[str] = Field(default_factory=list)
    alternatives: list[str] | None = None
    latency_ms: float = Field(default=0, alias="latencyMs")
    context_boost: int | None = Field(default=None, alias="contextBoost")
    chain_detections: list[ChainDetection] | None = Field(default=None, alias="chainDetections")
    risk_trend: str | None = Field(default=None, alias="riskTrend")


class HealthResponse(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    ok: bool
    version: str
    analyzers: list[str]
    auth: bool = False
    llm: bool = False
    sessions: bool = False
    policies: bool = False
    uptime: int = 0


class SessionInfo(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    session_id: str = Field(alias="sessionId")
    agent_id: str | None = Field(default=None, alias="agentId")
    started_at: int = Field(alias="startedAt")
    last_activity_at: int = Field(alias="lastActivityAt")
    action_count: int = Field(alias="actionCount")
    peak_score: int = Field(alias="peakScore")
    risk_trend: str = Field(alias="riskTrend")
    active_chains: list[str] = Field(default_factory=list, alias="activeChains")


class BatchResult(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    results: list[CheckResult]
    session_id: str = Field(alias="sessionId")
    chain_detections: list[ChainDetection] = Field(default_factory=list, alias="chainDetections")
    overall_level: RiskLevel = Field(alias="overallLevel")
    overall_score: int = Field(alias="overallScore")
