"""系统评价 / Meta 分析项目模型"""

import uuid
from datetime import datetime

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

from app.db import Base, new_uuid


class SystematicReview(Base):
    """系统评价 / Meta 分析项目"""

    __tablename__ = "systematic_reviews"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    user_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    tenant_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)

    title: Mapped[str] = mapped_column(String(500), nullable=False)
    objective: Mapped[str | None] = mapped_column(Text)
    protocol: Mapped[str | None] = mapped_column(Text)

    # 纳排标准
    inclusion_criteria: Mapped[dict] = mapped_column(JSON, default=list)  # list[str]
    exclusion_criteria: Mapped[dict] = mapped_column(JSON, default=list)  # list[str]

    # 检索策略
    databases_searched: Mapped[dict] = mapped_column(JSON, default=list)   # list[str]
    search_strategy: Mapped[dict] = mapped_column(JSON, default=dict)       # {pubmed: "..."}

    # PRISMA 阶段
    prisma_stage: Mapped[str] = mapped_column(String(20), default="identification")
    # identification → screening → eligibility → included

    status: Mapped[str] = mapped_column(String(20), default="draft")
    # draft / active / completed / archived

    notes: 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())

    # 关联
    literatures: Mapped[list["ReviewLiterature"]] = relationship(back_populates="review", cascade="all, delete-orphan")


class ReviewLiterature(Base):
    """系统评价中包含的文献"""

    __tablename__ = "review_literatures"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=new_uuid)
    review_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("systematic_reviews.id", ondelete="CASCADE"), nullable=False)
    literature_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("global_literature.id", ondelete="CASCADE"), nullable=False)

    # PRISMA 阶段
    stage: Mapped[str] = mapped_column(String(20), default="screening")
    # identification / screening / eligibility / included / excluded

    exclusion_reason: Mapped[str | None] = mapped_column(Text)
    notes: Mapped[str | None] = mapped_column(Text)

    # 质量评价（Cochrane RoB / Newcastle-Ottawa 等）
    quality_score: Mapped[str | None] = mapped_column(String(10))  # high / moderate / low / unclear
    quality_detail: Mapped[dict] = mapped_column(JSON, default=dict)  # {domain: "low", ...}

    # 评价级 PICO（与 GlobalLiterature.pico 隔离，多评价共享文献时独立编辑）
    pico: Mapped[dict | None] = mapped_column(JSON)

    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())

    # 反向关联
    review: Mapped["SystematicReview"] = relationship(back_populates="literatures")
