"""EditTemplate 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 EditTemplateStatus(StrEnum):
    """模板状态"""

    ACTIVE = "active"
    INACTIVE = "inactive"


@dataclass(slots=True)
class EditTemplate:
    """Phase 8 剪辑模板实体

    全局模板库中的模板，定义剪辑风格、配置参数和预览信息。
    不绑定到具体项目，可被多个 EditPlan 引用。
    """

    id: str
    name: str
    description: str = ""
    template_type: str = "default"
    config: dict[str, Any] = field(default_factory=dict)
    preview_url: str = ""
    sort_weight: int = 0
    status: EditTemplateStatus = EditTemplateStatus.ACTIVE
    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,
        name: str,
        *,
        description: str = "",
        template_type: str = "default",
        config: dict[str, Any] | None = None,
        preview_url: str = "",
        sort_weight: int = 0,
        status: EditTemplateStatus = EditTemplateStatus.ACTIVE,
    ) -> EditTemplate:
        """创建新模板实例"""
        clean_name = name.strip()
        if not clean_name:
            raise ValueError("模板名称不能为空")
        return cls(
            id=uuid4().hex,
            name=clean_name,
            description=description.strip(),
            template_type=template_type.strip() or "default",
            config=config or {},
            preview_url=preview_url.strip(),
            sort_weight=sort_weight,
            status=status,
        )

    def activate(self) -> None:
        """激活模板"""
        self.status = EditTemplateStatus.ACTIVE
        self.updated_at = datetime.now(timezone.utc)

    def deactivate(self) -> None:
        """停用模板"""
        self.status = EditTemplateStatus.INACTIVE
        self.updated_at = datetime.now(timezone.utc)

    @property
    def is_active(self) -> bool:
        """模板是否处于激活状态"""
        return self.status == EditTemplateStatus.ACTIVE
