#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：case_dependency.py
模块描述：用例依赖关系数据模型

作者：czj
创建日期：2026-07-12
"""

from datetime import datetime
from sqlalchemy import String, Integer, DateTime, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.database import Base


class CaseDependency(Base):
    """
    用例依赖关系模型

    定义测试用例之间的依赖关系，支持拓扑排序和条件执行。

    Attributes:
        id (str): 依赖关系唯一标识
        case_id (str): 用例ID（依赖方）
        depends_on_case_id (str): 被依赖的用例ID
        dependency_type (str): 依赖类型 (hard=强依赖/soft=弱依赖)
        order (int): 依赖顺序，当有多个依赖时决定优先级
        created_at (datetime): 创建时间

    依赖类型说明：
        - hard: 强依赖，前置用例必须成功，否则跳过执行
        - soft: 弱依赖，前置用例失败仅记录警告，仍继续执行

    Example:
        >>> dependency = CaseDependency(
        ...     case_id="case_002",
        ...     depends_on_case_id="case_001",
        ...     dependency_type="hard"
        ... )
    """

    __tablename__ = "case_dependencies"

    id: Mapped[str] = mapped_column(String(32), primary_key=True, comment="依赖关系ID")
    case_id: Mapped[str] = mapped_column(
        String(32),
        ForeignKey("test_cases.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
        comment="用例ID（依赖方）"
    )
    depends_on_case_id: Mapped[str] = mapped_column(
        String(32),
        ForeignKey("test_cases.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
        comment="被依赖的用例ID"
    )
    dependency_type: Mapped[str] = mapped_column(
        String(20),
        default="hard",
        comment="依赖类型: hard(强依赖)/soft(弱依赖)"
    )
    order: Mapped[int] = mapped_column(
        Integer,
        default=0,
        comment="依赖顺序（优先级）"
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime,
        default=datetime.utcnow,
        comment="创建时间"
    )

    # 关联关系
    case: Mapped["TestCase"] = relationship(
        "TestCase",
        foreign_keys=[case_id],
        back_populates="dependencies"
    )

    depends_on_case: Mapped["TestCase"] = relationship(
        "TestCase",
        foreign_keys=[depends_on_case_id],
        back_populates="dependents"
    )

    def __repr__(self) -> str:
        """字符串表示"""
        return f"<CaseDependency(id={self.id}, case_id={self.case_id}, depends_on={self.depends_on_case_id})>"

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

        Returns:
            dict: 依赖关系数据字典
        """
        return {
            "id": self.id,
            "case_id": self.case_id,
            "depends_on_case_id": self.depends_on_case_id,
            "dependency_type": self.dependency_type,
            "order": self.order,
            "created_at": self.created_at.isoformat() if self.created_at else None,
        }
