"""业务扩展模型：drug_approvals, guideline_versions, guideline_evidence, 审批流"""

import uuid
from datetime import date, datetime

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

from app.db import Base, new_uuid

TREATMENT_LINES = {
    "1L": "一线",
    "2L": "二线",
    "3L": "三线",
    "adjuvant": "辅助",
    "neoadjuvant": "新辅助",
    "maintenance": "维持",
}


def validate_treatment_line(v: str | None) -> str | None:
    if v is None:
        return None
    v = v.strip()
    if v not in TREATMENT_LINES:
        raise ValueError(
            f"Invalid treatment_line: {v}. Must be one of {list(TREATMENT_LINES.keys())}"
        )
    return v


class DrugApproval(Base):
    __tablename__ = "drug_approvals"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    drug_name: Mapped[str] = mapped_column(String(500), nullable=False)
    generic_name: Mapped[str] = mapped_column(String(500), nullable=False)
    target: Mapped[str | None] = mapped_column(String(200))
    indication: Mapped[str] = mapped_column(Text, nullable=False)
    cancer_type_tag_id: Mapped[uuid.UUID | None] = mapped_column(Uuid, ForeignKey("global_tags.id", ondelete="SET NULL"))
    approval_agency: Mapped[str] = mapped_column(String(10), nullable=False)
    approval_type: Mapped[str | None] = mapped_column(String(30))
    approval_date: Mapped[date] = mapped_column(Date, nullable=False)
    pivotal_trial_nct: Mapped[str | None] = mapped_column(String(20))
    pivotal_trial_pmid: Mapped[int | None] = mapped_column(Integer)
    source_url: Mapped[str | None] = mapped_column(String(1000))
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())

    __table_args__ = (
        Index("ix_drug_approvals_cancer_type_tag_id", "cancer_type_tag_id"),
        Index("ix_drug_approvals_target", "target"),
    )


class DrugLabel(Base):
    """FDA 药品标签数据（来自 openFDA labeling endpoint）

    label 按 set_id 唯一标识，一个 NDA/BLA 可有多个版本。
    """
    __tablename__ = "drug_labels"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    application_number: Mapped[str | None] = mapped_column(String(20), index=True)
    drug_name: Mapped[str] = mapped_column(String(500), nullable=False)
    generic_name: Mapped[str] = mapped_column(String(500), nullable=False)
    set_id: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
    effective_time: Mapped[str | None] = mapped_column(String(20))
    indications_and_usage: Mapped[str | None] = mapped_column(Text)
    mechanism_of_action: Mapped[str | None] = mapped_column(Text)
    clinical_studies: Mapped[str | None] = mapped_column(Text)
    warnings: Mapped[str | None] = mapped_column(Text)
    adverse_reactions: Mapped[str | None] = mapped_column(Text)
    nct_numbers: Mapped[list | None] = mapped_column(JSON)
    parsed_indications: Mapped[dict | None] = mapped_column(JSON)       # 结构化适应症 {cancers, lines, combinations}
    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())


class GuidelineVersion(Base):
    __tablename__ = "guideline_versions"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    guideline_source: Mapped[str] = mapped_column(String(10), nullable=False)
    cancer_type_tag_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("global_tags.id", ondelete="RESTRICT"), nullable=False)
    version: Mapped[str] = mapped_column(String(30), nullable=False)
    publish_date: Mapped[date] = mapped_column(Date, nullable=False)
    change_summary_zh: Mapped[str | None] = mapped_column(Text)
    change_summary_en: Mapped[str | None] = mapped_column(Text)
    pdf_url: Mapped[str | None] = mapped_column(String(1000))
    source_url: Mapped[str | None] = mapped_column(String(1000))
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())

    __table_args__ = (
        Index("ix_guideline_versions_cancer_type_tag_id", "cancer_type_tag_id"),
        Index("ix_guideline_versions_source_version", "guideline_source", "version"),
    )


class GuidelineEvidence(Base):
    __tablename__ = "guideline_evidence"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    guideline_version_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("guideline_versions.id", ondelete="CASCADE"), nullable=False)
    literature_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("global_literature.id", ondelete="CASCADE"), nullable=False)
    recommendation: Mapped[str | None] = mapped_column(Text)
    recommendation_level: Mapped[str | None] = mapped_column(String(10))
    treatment_line: Mapped[str | None] = mapped_column(String(20))
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())


class ApprovalWorkflow(Base):
    __tablename__ = "approval_workflows"

    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)
    literature_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("global_literature.id", ondelete="CASCADE"), nullable=False)
    submitted_by: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    status: Mapped[str] = mapped_column(String(20), default="pending")
    current_step: Mapped[int] = mapped_column(Integer, default=1)
    total_steps: Mapped[int] = mapped_column(Integer, default=1)
    comment: Mapped[str | None] = mapped_column(Text)
    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())


class AiProviderConfig(Base):
    __tablename__ = "ai_provider_config"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    provider: Mapped[str] = mapped_column(String(50), nullable=False, comment="deepseek/openai/claude")
    api_key: Mapped[str] = mapped_column(String(500), nullable=False)
    base_url: Mapped[str] = mapped_column(String(500), nullable=False)
    model_name: Mapped[str] = mapped_column(String(100), nullable=False)
    temperature: Mapped[float] = mapped_column(Integer, default=3)  # 0-10 stored as int, display as 0.0-1.0
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)
    updated_by: Mapped[uuid.UUID | None] = mapped_column(Uuid, ForeignKey("users.id", ondelete="SET NULL"))
    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())


class ApprovalStep(Base):
    __tablename__ = "approval_steps"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    workflow_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("approval_workflows.id", ondelete="CASCADE"), nullable=False)
    step_order: Mapped[int] = mapped_column(Integer, nullable=False)
    approver_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    status: Mapped[str] = mapped_column(String(20), default="pending")
    comment: Mapped[str | None] = mapped_column(Text)
    decided_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
