"""
Review Task Model

审核任务模型 - 支持过程中审核和生成后审核两种模式

## 审核模式说明

### 1. 过程中审核 (Process Review)
- 触发时机：Agent在流式输出过程中自主识别需要审核的内容
- 阻塞方式：阻塞式等待用户确认
- 消失方式：用户确认后自动销毁，不需要留存记录
- 交互位置：在聊天界面完成

### 2. 生成后审核 (Post-Creation Review)
- 触发时机：剧集生成完成后自动检查
- 触发源：根据用户配置的审核规则/Skill
- 阈值判断：根据阈值判断是否报告问题
- 存留方式：留存记录，用户可以确认问题、忽略问题、修改内容
"""
from pydantic import BaseModel, Field
from typing import Dict, List, Optional, Any
from datetime import datetime
from enum import Enum


# ============================================
# 枚举类型
# ============================================

class ReviewMode(str, Enum):
    """审核模式"""
    PROCESS = "process"      # 过程中审核
    POST_CREATION = "post_creation"  # 生成后审核


class ReviewTriggerSource(str, Enum):
    """审核触发来源"""
    AGENT_AUTO = "agent_auto"           # Agent自主识别
    USER_CONFIGURED_SKILL = "user_skill"  # 用户配置的Skill
    USER_CONFIGURED_RULE = "user_rule"  # 用户配置的规则
    MANUAL_REQUEST = "manual"               # 手动请求


class ReviewTaskStatus(str, Enum):
    """审核任务状态"""
    PENDING = "pending"          # 等待处理
    AWAITING_USER = "awaiting_user"  # 等待用户确认
    APPROVED = "approved"        # 已确认
    REJECTED = "rejected"        # 已拒绝
    MODIFIED = "modified"        # 已修改内容
    IGNORED = "ignored"          # 已忽略
    COMPLETED = "completed"      # 已完成（自动销毁）


class ReviewAction(str, Enum):
    """用户可执行的操作"""
    CONFIRM = "confirm"          # 确认继续
    MODIFY = "modify"            # 修改内容
    IGNORE = "ignore"             # 忽略问题
    OTHER = "other"               # 其他补充信息


# ============================================
# 审核任务模型
# ============================================

class ReviewTaskLocation(BaseModel):
    """审核任务位置信息"""
    episode_number: Optional[int] = Field(None, description="集数")
    scene_number: Optional[int] = Field(None, description="场景编号")
    section: Optional[str] = Field(None, description="章节/段落")
    line_number: Optional[int] = Field(None, description="行号")
    content_snippet: Optional[str] = Field(None, description="相关内容片段")


class ReviewTask(BaseModel):
    """
    审核任务

    包含问题类型、位置、严重程度等信息
    """
    id: str = Field(..., description="任务ID")
    project_id: str = Field(..., description="项目ID")
    episode_id: Optional[str] = Field(None, description="剧集ID")

    # 审核模式和来源
    mode: ReviewMode = Field(..., description="审核模式")
    trigger_source: ReviewTriggerSource = Field(..., description="触发来源")

    # 任务信息
    issue_type: str = Field(..., description="问题类型")
    issue_description: str = Field(..., description="问题描述")
    severity: str = Field(..., description="严重程度: low/medium/high")
    location: ReviewTaskLocation = Field(..., description="问题位置")

    # 审核配置来源
    review_config_id: Optional[str] = Field(None, description="触发的审核配置ID")
    skill_id: Optional[str] = Field(None, description="使用的Skill ID")
    rule_id: Optional[str] = Field(None, description="触发的规则ID")

    # 可用操作
    available_actions: List[ReviewAction] = Field(
        default_factory=list,
        description="用户可执行的操作列表"
    )

    # 状态和用户响应
    status: ReviewTaskStatus = Field(
        default=ReviewTaskStatus.PENDING,
        description="任务状态"
    )
    user_response: Optional[str] = Field(None, description="用户的响应内容")

    # 时间戳
    created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
    completed_at: Optional[datetime] = Field(None, description="完成时间")
    expires_at: Optional[datetime] = Field(None, description="过期时间（过程审核自动销毁）")

    # 附加信息
    context_data: Optional[Dict[str, Any]] = Field(
        default_factory=dict,
        description="附加上下文数据"
    )
    suggestion: Optional[str] = Field("", description="修改建议")


# ============================================
# 请求/响应模型
# ============================================

class ProcessReviewRequest(BaseModel):
    """
    过程中审核请求 - 由Agent推送
    """
    project_id: str
    issue_type: str
    issue_description: str
    severity: str  # low/medium/high
    location: ReviewTaskLocation
    trigger_source: ReviewTriggerSource = ReviewTriggerSource.AGENT_AUTO
    review_config_id: Optional[str] = None
    skill_id: Optional[str] = None
    rule_id: Optional[str] = None
    suggestion: Optional[str] = None


class ProcessReviewResponse(BaseModel):
    """
    过程中审核响应
    """
    task_id: str
    status: ReviewTaskStatus
    message: str


class UserReviewActionRequest(BaseModel):
    """
    用户审核操作请求
    """
    action: ReviewAction
    task_id: str
    user_response: Optional[str] = Field(None, description="用户补充信息")
    modified_content: Optional[str] = Field(None, description="修改后的内容")


class PostCreationReviewRequest(BaseModel):
    """
    生成后审核请求
    """
    project_id: str
    episode_id: str
    use_configured_rules: bool = Field(True, description="是否使用配置的规则")
    use_configured_skills: bool = Field(True, description="是否使用配置的Skills")
    dimensions: Optional[List[str]] = Field(None, description="指定审核维度")
    pass_threshold: Optional[float] = Field(None, description="通过阈值")


class PostCreationReviewResult(BaseModel):
    """
    生成后审核结果
    """
    task_count: int = Field(..., description="生成的任务数")
    passed: bool = Field(..., description="是否通过审核（没有高严重度问题）")
    tasks: List[ReviewTask] = Field(default_factory=list, description="审核任务列表")
    overall_score: Optional[float] = Field(None, description="总体分数")
