"""
Dramatiq Worker Starter 数据模型
================================

定义任务执行结果和元数据的 Pydantic 数据类
"""

from datetime import datetime
from typing import Any

from pydantic import BaseModel, Field


class TaskMetadata(BaseModel):
    """任务执行元数据"""

    start_datetime: str = Field(..., description="开始时间（ISO 格式）")
    end_datetime: str = Field(..., description="结束时间（ISO 格式）")
    duration_ms: int = Field(..., description="持续时间（毫秒）")
    queue_name: str = Field(..., description="队列名称")
    actor_name: str = Field(..., description="Actor 名称")
    worker_id: str = Field(..., description="Worker ID")
    exception: str | None = Field(default=None, description="异常信息（如果有）")

    @classmethod
    def from_runtime_info(
        cls,
        start_datetime: datetime,
        end_datetime: datetime,
        duration_ms: int,
        queue_name: str,
        actor_name: str,
        worker_id: str,
        exception: str | None = None,
    ) -> "TaskMetadata":
        """从运行时信息创建 TaskMetadata 实例"""
        return cls(
            start_datetime=start_datetime.isoformat(),
            end_datetime=end_datetime.isoformat(),
            duration_ms=duration_ms,
            queue_name=queue_name,
            actor_name=actor_name,
            worker_id=worker_id,
            exception=exception,
        )


class ErrorInfo(BaseModel):
    """错误信息"""

    type: str = Field(..., description="错误类型")
    message: str = Field(..., description="错误消息")


class ResultData(BaseModel):
    """任务执行结果数据"""

    result: Any = Field(default=None, description="执行结果")
    error: ErrorInfo | None = Field(default=None, description="错误信息（如果有）")
    metadata: TaskMetadata = Field(..., description="任务元数据")
