"""
Mid Platform models for Intent-Driven Agent.
[AC-IDMP-01~20] 中台统一响应协议模型
"""

import uuid
from datetime import datetime
from enum import Enum
from typing import Any

from pydantic import BaseModel, Field


class Mode(str, Enum):
    """[AC-IDMP-02] 执行模式"""
    AGENT = "agent"
    MICRO_FLOW = "micro_flow"
    FIXED = "fixed"
    TRANSFER = "transfer"


class SessionMode(str, Enum):
    """[AC-IDMP-09] 会话模式"""
    BOT_ACTIVE = "BOT_ACTIVE"
    HUMAN_ACTIVE = "HUMAN_ACTIVE"


class HighRiskScenario(str, Enum):
    """[AC-IDMP-20] 高风险场景最小集"""
    REFUND = "refund"
    COMPLAINT_ESCALATION = "complaint_escalation"
    PRIVACY_SENSITIVE_PROMISE = "privacy_sensitive_promise"
    TRANSFER = "transfer"


class ToolCallStatus(str, Enum):
    """[AC-IDMP-15] 工具调用状态"""
    OK = "ok"
    TIMEOUT = "timeout"
    ERROR = "error"
    REJECTED = "rejected"


class ToolType(str, Enum):
    """[AC-IDMP-19] 工具类型"""
    INTERNAL = "internal"
    MCP = "mcp"


class HistoryMessage(BaseModel):
    """[AC-IDMP-03] 已送达历史消息"""
    role: str = Field(..., description="消息角色: user/assistant/human")
    content: str = Field(..., description="消息内容")


class InterruptedSegment(BaseModel):
    """[AC-IDMP-04] 打断的分段"""
    segment_id: str = Field(..., description="分段ID")
    content: str = Field(..., description="分段内容")


class FeatureFlags(BaseModel):
    """[AC-IDMP-17] 特性开关"""
    agent_enabled: bool | None = Field(default=None, description="会话级 Agent 灰度开关")
    rollback_to_legacy: bool | None = Field(default=None, description="强制回滚传统链路")


class DialogueRequest(BaseModel):
    """[AC-IDMP-01~04] 会话响应请求"""
    session_id: str = Field(..., description="会话ID")
    user_id: str | None = Field(default=None, description="用户ID，用于记忆召回与更新")
    user_message: str = Field(..., min_length=1, max_length=2000, description="用户消息")
    history: list[HistoryMessage] = Field(default_factory=list, description="已送达历史")
    interrupted_segments: list[InterruptedSegment] | None = Field(default=None, description="打断的分段")
    feature_flags: FeatureFlags | None = Field(default=None, description="特性开关")
    scene: str | None = Field(default=None, description="场景标识，用于KB过滤，如 'open_consult', 'after_sale'")


class Segment(BaseModel):
    """[AC-IDMP-01] 响应分段"""
    segment_id: str = Field(..., description="分段ID")
    text: str = Field(..., description="分段文本")
    delay_after: int = Field(default=0, ge=0, description="分段后延迟(ms)")


class TimeoutProfile(BaseModel):
    """[AC-IDMP-12] 超时配置"""
    per_tool_timeout_ms: int | None = Field(default=30000, le=60000, description="单工具超时(ms)")
    end_to_end_timeout_ms: int | None = Field(default=120000, le=180000, description="端到端超时(ms)")


class MetricsSnapshot(BaseModel):
    """[AC-IDMP-18] 运行指标快照"""
    task_completion_rate: float | None = Field(default=None, ge=0, le=1, description="任务达成率")
    slot_completion_rate: float | None = Field(default=None, ge=0, le=1, description="槽位完整率")
    wrong_transfer_rate: float | None = Field(default=None, ge=0, le=1, description="误转人工率")
    no_recall_rate: float | None = Field(default=None, ge=0, le=1, description="无召回率")
    avg_latency_ms: float | None = Field(default=None, ge=0, description="平均时延(ms)")


class ToolCallTraceModel(BaseModel):
    """[AC-IDMP-15/19] 工具调用追踪 (Pydantic 模型)"""
    tool_name: str = Field(..., description="工具名称")
    tool_type: ToolType | None = Field(default=None, description="工具类型: internal/mcp")
    registry_version: str | None = Field(default=None, description="注册版本")
    auth_applied: bool | None = Field(default=None, description="是否应用鉴权")
    duration_ms: int = Field(..., ge=0, description="耗时(ms)")
    status: ToolCallStatus = Field(..., description="状态: ok/timeout/error/rejected")
    error_code: str | None = Field(default=None, description="错误码")
    args_digest: str | None = Field(default=None, description="参数摘要")
    result_digest: str | None = Field(default=None, description="结果摘要")


class TraceInfo(BaseModel):
    """[AC-IDMP-02/07] 追踪信息"""
    mode: Mode = Field(..., description="执行模式")
    intent: str | None = Field(default=None, description="意图")
    request_id: str | None = Field(default=None, description="请求ID")
    generation_id: str | None = Field(default=None, description="生成ID")
    guardrail_triggered: bool | None = Field(default=False, description="护栏是否触发")
    fallback_reason_code: str | None = Field(default=None, description="降级原因码")
    react_iterations: int | None = Field(default=None, ge=0, le=5, description="ReAct循环次数")
    timeout_profile: TimeoutProfile | None = Field(default=None, description="超时配置")
    metrics_snapshot: MetricsSnapshot | None = Field(default=None, description="指标快照")
    high_risk_policy_set: list[HighRiskScenario] | None = Field(
        default=None, 
        description="当前启用的高风险最小场景集"
    )
    tools_used: list[str] | None = Field(default=None, description="使用的工具列表")
    tool_calls: list[ToolCallTraceModel] | None = Field(default=None, description="工具调用追踪")
    step_kb_binding: dict[str, Any] | None = Field(default=None, description="[Step-KB-Binding] 步骤知识库绑定信息")


class DialogueResponse(BaseModel):
    """[AC-IDMP-01/02] 会话响应"""
    segments: list[Segment] = Field(..., description="响应分段列表")
    trace: TraceInfo = Field(..., description="追踪信息")


class ReportedMessage(BaseModel):
    """[AC-IDMP-08] 上报的消息"""
    role: str = Field(..., description="角色: user/assistant/human/system")
    content: str = Field(..., description="消息内容")
    source: str = Field(..., description="来源: bot/human/channel")
    timestamp: datetime = Field(..., description="时间戳")
    segment_id: str | None = Field(default=None, description="分段ID")


class MessageReportRequest(BaseModel):
    """[AC-IDMP-08] 消息上报请求"""
    session_id: str = Field(..., description="会话ID")
    messages: list[ReportedMessage] = Field(..., description="消息列表")


class SwitchModeRequest(BaseModel):
    """[AC-IDMP-09] 切换模式请求"""
    mode: SessionMode = Field(..., description="目标模式")
    reason: str | None = Field(default=None, description="切换原因")


class SwitchModeResponse(BaseModel):
    """[AC-IDMP-09] 切换模式响应"""
    session_id: str = Field(..., description="会话ID")
    mode: SessionMode = Field(..., description="当前模式")


from app.models.mid.memory import (
    RecallRequest,
    RecallResponse,
    UpdateRequest,
    MemoryProfile,
    MemoryFact,
    MemoryPreferences,
)
from app.models.mid.tool_trace import (
    ToolCallTrace,
    ToolCallBuilder,
    ToolCallStatus as ToolCallStatusEnum,
    ToolType as ToolTypeEnum,
)
from app.models.mid.tool_registry import (
    ToolDefinition,
    ToolAuthConfig,
    ToolTimeoutPolicy,
    ToolRegistryEntity,
    ToolRegistryCreate,
    ToolRegistryUpdate,
)

__all__ = [
    "Mode",
    "SessionMode",
    "HighRiskScenario",
    "ToolCallStatus",
    "ToolType",
    "HistoryMessage",
    "InterruptedSegment",
    "FeatureFlags",
    "DialogueRequest",
    "Segment",
    "TimeoutProfile",
    "MetricsSnapshot",
    "ToolCallTraceModel",
    "TraceInfo",
    "DialogueResponse",
    "ReportedMessage",
    "MessageReportRequest",
    "SwitchModeRequest",
    "SwitchModeResponse",
    "RecallRequest",
    "RecallResponse",
    "UpdateRequest",
    "MemoryProfile",
    "MemoryFact",
    "MemoryPreferences",
    "ToolCallTrace",
    "ToolCallBuilder",
    "ToolCallStatusEnum",
    "ToolTypeEnum",
    "ToolDefinition",
    "ToolAuthConfig",
    "ToolTimeoutPolicy",
    "ToolRegistryEntity",
    "ToolRegistryCreate",
    "ToolRegistryUpdate",
]
