"""MDT 多学科协作专用模型"""

import uuid
from datetime import datetime

from sqlalchemy import JSON, DateTime, ForeignKey, Integer, String, Text, Uuid, func
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.db import Base, new_uuid


class MDTCase(Base):
    __tablename__ = "mdt_cases"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    tenant_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
    title: Mapped[str] = mapped_column(String(300), nullable=False)
    patient_summary: Mapped[str] = mapped_column(Text, nullable=False)
    cancer_type: Mapped[str | None] = mapped_column(String(100))
    status: Mapped[str] = mapped_column(String(20), default="open")
    created_by: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id", ondelete="SET NULL"), nullable=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())

    decisions: Mapped[list["MDTDecision"]] = relationship(
        "MDTDecision", back_populates="case", cascade="all, delete-orphan"
    )


class MDTDecision(Base):
    __tablename__ = "mdt_decisions"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    case_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("mdt_cases.id", ondelete="CASCADE"), nullable=False)
    conclusion: Mapped[str] = mapped_column(Text, nullable=False)
    meeting_date: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
    participants: Mapped[dict] = mapped_column(JSON, default=list)  # [{user_id, display_name, role}]
    decided_by: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
    decided_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())

    case: Mapped["MDTCase"] = relationship("MDTCase", back_populates="decisions")


class MDTEvidence(Base):
    __tablename__ = "mdt_evidence"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    case_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("mdt_cases.id", ondelete="CASCADE"), nullable=False)
    decision_id: Mapped[uuid.UUID | None] = mapped_column(Uuid, ForeignKey("mdt_decisions.id", ondelete="SET NULL"))
    literature_id: Mapped[uuid.UUID | None] = mapped_column(Uuid, ForeignKey("global_literature.id", ondelete="SET NULL"))
    pmid: Mapped[int | None] = mapped_column(Integer)
    citation: Mapped[str | None] = mapped_column(Text)
    relevance_note: Mapped[str | None] = mapped_column(Text)
    added_by: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
