from pydantic import BaseModel, Field

from app.enums.generation_status import (
    GenerationStatus,
    GenerationType,
    DURATIONS,
    ASPECT_RATIOS,
    RESOLUTIONS,
    IMAGE_SIZES,
)
from app.schemas.common import NaiveDatetime, NaiveDatetimeOptional
from app.services.operation_log import log_operation


class OptimizeParams(BaseModel):
    project_id: str
    prompt: str = Field(..., max_length=500)
    gen_type: GenerationType = Field(GenerationType.video, description="生成类型：video-视频，image-图片")
    duration: int | None = Field(None, description="视频时长（秒），视频生成必填")
    image_size: str | None = Field(None, description="画面分辨率，图片生成使用")
    image_proportion: str | None = Field(None, description="图片比例，图片生成使用")
    image_px: str | None = Field(None, description="图片像素大小，图片生成使用")
    references: list[dict] | None = None
    idempotency_key: str | None = Field(None, max_length=64, description="幂等键，防止重复请求")


class GenerateParams(BaseModel):
    aspect_ratio: str | None = None
    resolution: str | None = None
    image_size: str | None = None


class OptimizeResult(BaseModel):
    optimized_prompt: str
    text_credits_cost: float
    # text_tokens_used: int
    record: "GenerationRecordOut"

class GenerationRecordOut(BaseModel):
    id: str
    project_id: str
    project_name: str
    original_prompt: str
    optimized_prompt: str | None = None
    gen_type: str = "video"
    duration: int | None = None
    aspect_ratio: str | None = None
    resolution: str | None = None
    image_size: str | None = None
    image_proportion: str | None = None
    image_px: str | None = None
    status: str
    video_url: str | None = None
    video_cover_url: str | None = None
    image_url: str | None = None
    references: list[dict] | None = None
    text_credits_cost: float = 0.0
    # text_tokens_used: int = 0
    credits_cost: float = 0.0
    # video_tokens_used: int = 0
    # image_tokens_used: int = 0
    error_message: str | None = None
    created_at: NaiveDatetime
    generated_at: NaiveDatetimeOptional = None

    model_config = {"from_attributes": True}


class GenerationRecordPageListOut(BaseModel):
    """生成记录分页返回API。"""
    page: int = Field(..., description="当前日期分组分页页码")
    page_size: int = Field(..., description="当前每页返回的日期分组数量")
    total: int = Field(..., description="当前生成日期下的生成成功记录总数")
    items: list[GenerationRecordOut] = Field(default_factory=list,)

class UpdatePromptRequest(BaseModel):
    optimized_prompt: str = Field(..., max_length=2000)


OptimizeResult.model_rebuild()
