from __future__ import annotations

import uuid
from datetime import datetime

from sqlalchemy import (
    DateTime,
    ForeignKey,
    ForeignKeyConstraint,
    Index,
    String,
    Text,
    UniqueConstraint,
    func,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.types import JSON

from app.db.base_class import Base


class HermesRiskReport(Base):
    __tablename__ = "hermes_risk_reports"
    __table_args__ = (
        UniqueConstraint("tenant_id", "id", name="uq_hermes_risk_reports_tenant_id"),
        ForeignKeyConstraint(
            ["tenant_id", "claim_id"],
            ["expense_claims.tenant_id", "expense_claims.id"],
            name="fk_hermes_risk_reports_tenant_claim",
            ondelete="CASCADE",
        ),
        ForeignKeyConstraint(
            ["tenant_id", "execution_log_id"],
            ["hermes_task_execution_logs.tenant_id", "hermes_task_execution_logs.id"],
            name="fk_hermes_risk_reports_tenant_log",
            ondelete="CASCADE",
        ),
        Index("ix_hermes_risk_reports_tenant_status", "tenant_id", "status"),
    )

    id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    tenant_id: Mapped[str] = mapped_column(
        ForeignKey("tenants.tenant_id", ondelete="RESTRICT"),
        nullable=False,
        server_default="default",
    )
    claim_id: Mapped[str] = mapped_column(index=True)
    execution_log_id: Mapped[str] = mapped_column(index=True)

    risk_level: Mapped[str] = mapped_column(String(20), index=True)
    risk_type: Mapped[str] = mapped_column(String(50), index=True)
    risk_description: Mapped[str] = mapped_column(Text())

    related_claim_ids: Mapped[list[str]] = mapped_column(JSON, default=list)
    status: Mapped[str] = mapped_column(String(30), default="pending_review", index=True)

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

    claim = relationship(
        "ExpenseClaim",
        foreign_keys=[tenant_id, claim_id],
        overlaps="execution_log",
    )
    execution_log = relationship(
        "HermesTaskExecutionLog",
        foreign_keys=[tenant_id, execution_log_id],
        overlaps="claim",
    )
