from __future__ import annotations

import uuid
from datetime import datetime
from typing import Any

from sqlalchemy import Boolean, DateTime, Index, String, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.types import JSON

from app.db.base_class import Base


class GoldenCase(Base):
    """风险规则回归门禁用的黄金用例。

    由运营手动维护（或从已确认风险观测导入），在规则发布前作为回归集执行，
    100% 通过才放行。``values_json`` 复用 ``AgentAssetRiskRuleSampleCase.values``
    的扁平字典格式，``expected_hit`` / ``expected_severity`` 作为 ground truth。
    """

    __tablename__ = "golden_cases"
    __table_args__ = (
        Index("ix_golden_cases_rule_code_status", "rule_code", "status"),
        Index("ix_golden_cases_scene_status", "scene", "status"),
    )

    id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    case_key: Mapped[str] = mapped_column(String(160), unique=True, index=True)
    rule_code: Mapped[str | None] = mapped_column(String(120), nullable=True, index=True)
    scene: Mapped[str] = mapped_column(String(50), default="", index=True)

    name: Mapped[str] = mapped_column(String(120), default="")
    values_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
    expected_hit: Mapped[bool] = mapped_column(Boolean, default=True)
    expected_severity: Mapped[str | None] = mapped_column(String(20), nullable=True)
    note: Mapped[str | None] = mapped_column(Text(), nullable=True)

    status: Mapped[str] = mapped_column(String(20), default="active", index=True)
    source: Mapped[str] = mapped_column(String(30), default="manual")

    created_at: Mapped[datetime] = mapped_column(DateTime, default=func.now(), server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime,
        default=func.now(),
        onupdate=func.now(),
        server_default=func.now(),
    )
