"""PDF 高亮/划线/批注 API"""

import uuid as _uuid

from typing import Literal

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
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.interaction import UserPdfHighlight
from app.models.literature import GlobalLiterature

router = APIRouter()

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

class HighlightCreate(BaseModel):
    highlight_type: Literal["highlight", "underline", "strikethrough", "free_text"]
    page_number: int
    position: dict = {}
    text: str | None = None
    note: str | None = None
    color: str = "#ffff00"

class HighlightUpdate(BaseModel):
    note: str | None = None
    color: str | None = None

@router.get("/{pmid}", summary="高亮列表")
async def list_highlights(pmid: int, db: AsyncSession = Depends(get_db), user: dict = Depends(get_current_user)):
    lit = (await db.execute(select(GlobalLiterature.id).where(GlobalLiterature.pmid == pmid))).scalar()
    if not lit: raise HTTPException(404)
    result = await db.execute(
        select(UserPdfHighlight).where(
            UserPdfHighlight.user_id == uid(user),
            UserPdfHighlight.literature_id == lit,
        ).order_by(UserPdfHighlight.page_number.asc())
    )
    items = result.scalars().all()
    return [{"id": str(h.id), "type": h.highlight_type, "page": h.page_number, "position": h.position,
              "text": h.text, "note": h.note, "color": h.color,
              "created_at": h.created_at.isoformat() if h.created_at else None} for h in items]

@router.post("/{pmid}", summary="创建高亮")
async def create_highlight(pmid: int, req: HighlightCreate, db: AsyncSession = Depends(get_db), user: dict = Depends(get_current_user)):
    lit = (await db.execute(select(GlobalLiterature.id).where(GlobalLiterature.pmid == pmid))).scalar()
    if not lit: raise HTTPException(404)
    h = UserPdfHighlight(user_id=uid(user), literature_id=lit, highlight_type=req.highlight_type,
                          page_number=req.page_number, position=req.position, text=req.text,
                          note=req.note, color=req.color)
    db.add(h); await db.commit()
    return {"status": "created", "id": str(h.id)}

@router.put("/{hid}", summary="更新高亮")
async def update_highlight(hid: str, req: HighlightUpdate, db: AsyncSession = Depends(get_db), user: dict = Depends(get_current_user)):
    try:
        hid_uuid = _uuid.UUID(hid)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid highlight ID")
    h = (await db.execute(select(UserPdfHighlight).where(UserPdfHighlight.id == hid_uuid))).scalar()
    if not h: raise HTTPException(404)
    if h.user_id != uid(user): raise HTTPException(403, detail="Not your highlight")
    if req.note is not None: h.note = req.note
    if req.color is not None: h.color = req.color
    await db.commit()
    return {"status": "updated"}

@router.delete("/{hid}", summary="删除高亮")
async def delete_highlight(hid: str, db: AsyncSession = Depends(get_db), user: dict = Depends(get_current_user)):
    try:
        hid_uuid = _uuid.UUID(hid)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid highlight ID")
    h = (await db.execute(select(UserPdfHighlight).where(UserPdfHighlight.id == hid_uuid))).scalar()
    if not h: raise HTTPException(404)
    if h.user_id != uid(user): raise HTTPException(403, detail="Not your highlight")
    await db.delete(h); await db.commit()
    return {"status": "deleted"}
