from __future__ import annotations

from datetime import date as dt_date

from pydantic import BaseModel


def cap_pub_date(d: dt_date | None) -> str | None:
    """Format pub_date to ISO string, capping future dates to today."""
    if d is None:
        return None
    return min(d, dt_date.today()).isoformat()
class PublicLiteratureCard(BaseModel):
    """公开 Feed 卡片（未登录可见）：不含研究设计、试验注册等增值字段"""
    id: str
    pmid: int
    title: str
    first_author: str = ""
    affiliation: str | None = None
    journal: str | None = None
    pub_date: str | None = None
    article_date: str | None = None
    doi: str | None = None
    pmc_id: str | None = None
    is_oa: bool = False
    cited_by_count: int = 0
    pub_types: list[str] = []
    tags: list[dict] = []
    ai_summary: str | None = None
    retracted: bool = False
    is_negative_result: bool = False
    created_at: str | None = None
    updated_at: str | None = None

    model_config = {"from_attributes": True}


class LiteratureCard(BaseModel):
    id: str
    pmid: int
    title: str
    first_author: str = ""
    affiliation: str | None = None     # 第一作者机构
    journal: str | None = None
    pub_date: str | None = None
    article_date: str | None = None
    doi: str | None = None
    pmc_id: str | None = None
    is_oa: bool = False
    cited_by_count: int = 0
    pub_types: list[str] = []
    tags: list[dict] = []
    ai_summary: str | None = None
    priority: str | None = None
    is_read: bool = False
    study_design: dict | None = None
    trial_reg: dict | None = None
    retracted: bool = False
    is_negative_result: bool = False
    rating: int | None = None
    personal_tags: list[str] = []
    reading_status: str = "unread"
    rct_detection: dict | None = None
    created_at: str | None = None
    updated_at: str | None = None

    model_config = {"from_attributes": True}


class PublicLiteratureDetail(BaseModel):
    """公开详情（未登录可见）：基本信息 + PubMed 原始元数据，不含平台增值数据"""
    id: str
    pmid: int
    title: str
    abstract: str | None = None
    authors: list[dict] = []
    affiliation: str | None = None
    doi: str | None = None
    pmc_id: str | None = None
    is_oa: bool = False
    cited_by_count: int = 0
    journal: str | None = None
    journal_issn: str | None = None
    volume: str | None = None
    issue: str | None = None
    pages: str | None = None
    pub_date: str | None = None
    pub_year: int | None = None
    pub_types: list[str] = []
    keywords: list[str] = []
    tags: list[dict] = []
    language: str = "en"
    retracted: bool = False
    retraction_details: dict | None = None
    is_negative_result: bool = False
    # PubMed 原始元数据（非平台增值）
    grants: list[dict] = []
    chemical_list: list[dict] = []
    gene_symbols: list[str] = []
    databank_list: list[dict] = []
    suppl_mesh_list: list[dict] = []
    num_refs: int | None = None
    publication_status: str | None = None
    article_date: str | None = None
    created_at: str | None = None
    updated_at: str | None = None

    model_config = {"from_attributes": True}

    # 平台增值数据（仅在 LiteratureDetail 中返回）：
    # full_text_sections, pre_extracted_data, pico, ai_summary, study_design,
    # trial_reg, rct_detection, license_info, negative_result_details


class LiteratureDetail(BaseModel):
    """完整详情（需登录）：含全部平台增值数据"""
    id: str
    pmid: int
    title: str
    abstract: str | None = None
    authors: list[dict] = []
    affiliation: str | None = None     # 第一作者机构
    doi: str | None = None
    pmc_id: str | None = None
    is_oa: bool = False
    cited_by_count: int = 0
    journal: str | None = None
    journal_issn: str | None = None
    volume: str | None = None
    issue: str | None = None
    pages: str | None = None
    pub_date: str | None = None
    pub_year: int | None = None
    pub_types: list[str] = []
    grants: list[dict] = []
    keywords: list[str] = []
    tags: list[dict] = []
    ai_summary: str | None = None
    language: str = "en"
    study_design: dict | None = None
    trial_reg: dict | None = None
    pico: dict | None = None
    retracted: bool = False
    retraction_details: dict | None = None
    is_negative_result: bool = False
    negative_result_details: dict | None = None
    rct_detection: dict | None = None
    license_info: dict | None = None
    pre_extracted_data: dict | None = None
    reading_status: str | None = None
    full_text_sections: dict | None = None
    chemical_list: list[dict] = []
    gene_symbols: list[str] = []
    num_refs: int | None = None
    publication_status: str | None = None
    article_date: str | None = None
    databank_list: list[dict] = []
    suppl_mesh_list: list[dict] = []
    created_at: str | None = None
    updated_at: str | None = None

    model_config = {"from_attributes": True}


class FeedResponse(BaseModel):
    items: list[LiteratureCard]
    total: int
    date: str
    must_read: int = 0
    recommended: int = 0
    related: int = 0


class PublicFeedResponse(BaseModel):
    """公开 Feed 响应：使用 PublicLiteratureCard"""
    items: list[PublicLiteratureCard]
    total: int
    date: str
    must_read: int = 0
    recommended: int = 0
    related: int = 0


class SearchFilters(BaseModel):
    q: str | None = None
    tag_ids: list[str] | None = None
    year_from: int | None = None
    year_to: int | None = None
    journal_tiers: list[str] | None = None
    pub_types: list[str] | None = None
    study_design: str | None = None  # interventional / observational / synthesis / etc
