"""AI 摘要 API — 使用 global_literature.ai_summary JSON 列存储"""

import uuid

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.permissions import get_current_user
from app.db import get_db
from app.models.literature import GlobalLiterature

router = APIRouter()

def uid(u: dict) -> uuid.UUID:
    return uuid.UUID(u["sub"])


@router.post("/generate/{pmid}", response_model=dict, summary="生成摘要")
async def generate_ai_summary(
    pmid: int,
    mode: str = Query("one_liner", description="one_liner | structured | implication"),
    db: AsyncSession = Depends(get_db),
    user: dict = Depends(get_current_user),
):
    """为单篇文献生成 AI 摘要（仅在 Pro+ 方案可用）"""
    result = await db.execute(select(GlobalLiterature).where(GlobalLiterature.pmid == pmid))
    lit = result.scalar()
    if not lit: raise HTTPException(status_code=404)
    if not lit.abstract: raise HTTPException(status_code=400, detail="No abstract available")

    from app.services.ai_summary import generate_clinical_implication, generate_one_liner, generate_structured_summary

    if mode == "one_liner":
        summary = await generate_one_liner(lit.title, lit.abstract)
    elif mode == "structured":
        summary = await generate_structured_summary(lit.title, lit.abstract)
    elif mode == "implication":
        summary = await generate_clinical_implication(lit.title, lit.abstract)
    else:
        raise HTTPException(status_code=400)

    if not summary:
        raise HTTPException(status_code=503, detail="AI service unavailable")

    # 持久化到 ai_summary JSON 列，按 mode 存取
    curr = dict(lit.ai_summary or {})
    curr[mode] = summary
    lit.ai_summary = curr
    await db.commit()

    return {"pmid": pmid, "mode": mode, "summary": summary}


@router.post("/batch-generate", response_model=dict, summary="批量生成")
async def batch_generate_summaries(
    mode: str = Query("one_liner"),
    limit: int = Query(20, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
    user: dict = Depends(get_current_user),
):
    """批量生成 AI 摘要（对最近无此模式摘要的文献）"""
    result = await db.execute(
        select(GlobalLiterature).order_by(GlobalLiterature.pub_date.desc().nullslast()).limit(limit)
    )
    articles = result.scalars().all()

    from app.services.ai_summary import generate_one_liner
    generated = 0
    for lit in articles:
        if not lit.abstract: continue
        # 跳过已有该模式摘要的文献
        curr = lit.ai_summary or {}
        if curr.get(mode):
            continue
        summary = await generate_one_liner(lit.title, lit.abstract)
        if summary:
            curr[mode] = summary
            lit.ai_summary = curr
            generated += 1

    await db.commit()
    return {"generated": generated, "total": len(articles), "mode": mode}


@router.get("/preview/{pmid}", summary="获取摘要")
async def get_ai_summary(
    pmid: int,
    db: AsyncSession = Depends(get_db),
):
    """获取已缓存的 AI 摘要"""
    result = await db.execute(select(GlobalLiterature).where(GlobalLiterature.pmid == pmid))
    lit = result.scalar()
    if not lit: raise HTTPException(status_code=404)

    return {"pmid": pmid, "summaries_by_mode": lit.ai_summary or {}}
