#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：case_result.py
模块描述：用例执行结果数据库模型定义

作者：czj
创建日期：2026-07-09
最后修改：2026-07-09
"""

from datetime import datetime
from typing import Optional
from sqlalchemy import String, Integer, Float, JSON, DateTime, Text, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.database import Base


class CaseResult(Base):
    """
    用例执行结果数据库模型

    记录单个测试用例在一次执行中的结果详情。

    Attributes:
        id (str): 结果唯一标识
        execution_id (str): 关联的执行记录ID
        case_id (str): 关联的测试用例ID
        case_name (str): 用例名称（冗余存储，便于查询）
        status (str): 执行状态 (passed/failed/skipped)
        duration (float): 耗时（秒）
        start_time (datetime): 开始时间
        end_time (datetime): 结束时间
        retry_count (int): 重试次数
        error_message (str): 错误信息
        steps_result (list): 各步骤执行结果，JSON 格式

    Example:
        >>> case_result = CaseResult(
        ...     id="result_abc123",
        ...     execution_id="exec_xyz",
        ...     case_id="case_001",
        ...     case_name="正常登录测试",
        ...     status="passed"
        ... )
    """

    __tablename__ = "case_results"

    id: Mapped[str] = mapped_column(String(64), primary_key=True, comment="结果ID")
    execution_id: Mapped[str] = mapped_column(
        String(64),
        ForeignKey("executions.id", ondelete="CASCADE"),
        nullable=False,
        comment="执行记录ID"
    )
    case_id: Mapped[str] = mapped_column(
        String(64),
        ForeignKey("test_cases.id", ondelete="SET NULL"),
        nullable=True,
        comment="用例ID"
    )
    case_name: Mapped[str] = mapped_column(String(200), default="", comment="用例名称")
    status: Mapped[str] = mapped_column(
        String(20),
        default="pending",
        comment="状态: pending/running/passed/failed/skipped"
    )
    duration: Mapped[float] = mapped_column(Float, default=0.0, comment="耗时(秒)")
    start_time: Mapped[Optional[datetime]] = mapped_column(
        DateTime,
        nullable=True,
        comment="开始时间"
    )
    end_time: Mapped[Optional[datetime]] = mapped_column(
        DateTime,
        nullable=True,
        comment="结束时间"
    )
    retry_count: Mapped[int] = mapped_column(Integer, default=0, comment="重试次数")
    error_message: Mapped[str] = mapped_column(Text, nullable=True, default="", comment="错误信息")
    steps_result: Mapped[list] = mapped_column(JSON, default=list, comment="步骤结果")
    created_at: Mapped[datetime] = mapped_column(
        DateTime,
        default=datetime.utcnow,
        comment="创建时间"
    )

    # 关联执行记录（多对一）
    execution: Mapped["Execution"] = relationship(
        "Execution",
        back_populates="case_results"
    )

    def __repr__(self) -> str:
        """字符串表示"""
        return f"<CaseResult(id={self.id}, case_name={self.case_name}, status={self.status})>"

    def to_dict(self) -> dict:
        """
        转换为字典

        Returns:
            dict: 用例结果数据字典
        """
        return {
            "id": self.id,
            "execution_id": self.execution_id,
            "case_id": self.case_id,
            "case_name": self.case_name,
            "status": self.status,
            "duration": self.duration,
            "start_time": self.start_time.isoformat() if self.start_time else None,
            "end_time": self.end_time.isoformat() if self.end_time else None,
            "retry_count": self.retry_count,
            "error_message": self.error_message,
            "steps_result": self.steps_result or [],
            "created_at": self.created_at.isoformat() if self.created_at else None,
        }
