"""EditPlan domain entity for Phase 8 模板编排引擎."""

from __future__ import annotations

import sys
from dataclasses import dataclass, field
from datetime import datetime, timezone

if sys.version_info >= (3, 11):
    from enum import StrEnum
else:
    from enum import Enum

    class StrEnum(str, Enum):
        pass


from typing import Any
from uuid import uuid4


class EditPlanStatus(StrEnum):
    """剪辑计划状态"""

    DRAFT = "draft"
    EDITING = "editing"
    RENDERING = "rendering"
    COMPLETED = "completed"
    FAILED = "failed"


@dataclass(slots=True)
class EditPlan:
    """Phase 8 剪辑计划实体

    基于某个 EditTemplate 创建的剪辑计划，包含具体的配置和状态追踪。
    状态流转：draft → editing → rendering → completed / failed
    """

    id: str
    template_id: str
    name: str
    status: EditPlanStatus = EditPlanStatus.DRAFT
    total_duration: float = 0.0
    source_edit_plan_id: str = ""
    project_id: str = ""
    created_by_user_id: str = ""
    config: dict[str, Any] = field(default_factory=dict)
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
    updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))

    @classmethod
    def create(
        cls,
        template_id: str,
        name: str,
        *,
        config: dict[str, Any] | None = None,
        total_duration: float = 0.0,
        source_edit_plan_id: str = "",
        project_id: str = "",
        created_by_user_id: str = "",
    ) -> EditPlan:
        """创建新剪辑计划实例"""
        clean_name = name.strip()
        if not clean_name:
            raise ValueError("计划名称不能为空")
        if not template_id.strip():
            raise ValueError("template_id 不能为空")
        return cls(
            id=uuid4().hex,
            template_id=template_id.strip(),
            name=clean_name,
            status=EditPlanStatus.DRAFT,
            total_duration=total_duration,
            source_edit_plan_id=source_edit_plan_id.strip(),
            project_id=project_id.strip(),
            created_by_user_id=created_by_user_id.strip(),
            config=config or {},
        )

    def start_editing(self) -> None:
        """开始编辑"""
        if self.status != EditPlanStatus.DRAFT:
            raise ValueError(f"只有 draft 状态的计划可以开始编辑，当前状态: {self.status}")
        self.status = EditPlanStatus.EDITING
        self.updated_at = datetime.now(timezone.utc)

    def start_rendering(self) -> None:
        """开始渲染"""
        if self.status != EditPlanStatus.EDITING:
            raise ValueError(f"只有 editing 状态的计划可以开始渲染，当前状态: {self.status}")
        self.status = EditPlanStatus.RENDERING
        self.updated_at = datetime.now(timezone.utc)

    def mark_completed(self) -> None:
        """标记为完成"""
        if self.status != EditPlanStatus.RENDERING:
            raise ValueError(f"只有 rendering 状态的计划可以标记完成，当前状态: {self.status}")
        self.status = EditPlanStatus.COMPLETED
        self.updated_at = datetime.now(timezone.utc)

    def mark_failed(self) -> None:
        """标记为失败"""
        if self.status != EditPlanStatus.RENDERING:
            raise ValueError(f"只有 rendering 状态的计划可以标记失败，当前状态: {self.status}")
        self.status = EditPlanStatus.FAILED
        self.updated_at = datetime.now(timezone.utc)

    def reset_to_draft(self) -> None:
        """重置为草稿状态（仅从 failed 状态可重置）"""
        if self.status != EditPlanStatus.FAILED:
            raise ValueError(f"只有 failed 状态的计划可以重置，当前状态: {self.status}")
        self.status = EditPlanStatus.DRAFT
        self.updated_at = datetime.now(timezone.utc)
