from __future__ import annotations

# pyright: reportMissingImports=false

"""
wiki_api — FastAPI APIRouter 기반 InsuWiki CRUD API.

라우터: /api/wiki
"""

from typing import Any

from fastapi import APIRouter, HTTPException, Query

from .wiki_store import WikiStore

router = APIRouter(prefix="/api/wiki", tags=["wiki"])

# ---------------------------------------------------------------------------
# Lazy WikiStore 싱글턴
# ---------------------------------------------------------------------------

_store: WikiStore | None = None


def get_store() -> WikiStore:
    global _store
    if _store is None:
        _store = WikiStore()
    return _store


# ---------------------------------------------------------------------------
# 엔드포인트
# ---------------------------------------------------------------------------


@router.get("/entries")
def list_entries(
    category: str | None = Query(default=None),
    status: str | None = Query(default=None),
    limit: int = Query(default=50, ge=1, le=500),
    offset: int = Query(default=0, ge=0),
) -> list[dict[str, Any]]:
    """위키 항목 목록 조회."""
    return get_store().list_entries(
        category=category,
        status=status,
        limit=limit,
        offset=offset,
    )


@router.post("/entries", status_code=201)
def create_entry(body: dict[str, Any]) -> dict[str, Any]:
    """새 위키 항목 생성."""
    entry_id = get_store().insert_entry(body)
    entry = get_store().get_entry(entry_id)
    if entry is None:
        raise HTTPException(status_code=500, detail="항목 생성 후 조회 실패")
    return entry


@router.get("/entries/{entry_id}")
def get_entry(entry_id: str) -> dict[str, Any]:
    """단건 위키 항목 조회."""
    entry = get_store().get_entry(entry_id)
    if entry is None:
        raise HTTPException(
            status_code=404, detail=f"항목을 찾을 수 없습니다: {entry_id}"
        )
    return entry


@router.put("/entries/{entry_id}")
def update_entry(entry_id: str, body: dict[str, Any]) -> dict[str, Any]:
    """위키 항목 부분 업데이트."""
    updated = get_store().update_entry(entry_id, body)
    if not updated:
        raise HTTPException(
            status_code=404, detail=f"항목을 찾을 수 없습니다: {entry_id}"
        )
    entry = get_store().get_entry(entry_id)
    if entry is None:
        raise HTTPException(
            status_code=404, detail=f"항목을 찾을 수 없습니다: {entry_id}"
        )
    return entry


@router.delete("/entries/{entry_id}", status_code=204)
def delete_entry(entry_id: str) -> None:
    """위키 항목 삭제."""
    deleted = get_store().delete_entry(entry_id)
    if not deleted:
        raise HTTPException(
            status_code=404, detail=f"항목을 찾을 수 없습니다: {entry_id}"
        )


@router.post("/entries/{entry_id}/approve")
def approve_entry(entry_id: str) -> dict[str, Any]:
    """위키 항목 승인 (status → approved)."""
    ok = get_store().approve_entry(entry_id)
    if not ok:
        raise HTTPException(
            status_code=404, detail=f"항목을 찾을 수 없습니다: {entry_id}"
        )
    entry = get_store().get_entry(entry_id)
    if entry is None:
        raise HTTPException(
            status_code=404, detail=f"항목을 찾을 수 없습니다: {entry_id}"
        )
    return entry


@router.post("/entries/{entry_id}/reject")
def reject_entry(entry_id: str) -> dict[str, Any]:
    """위키 항목 반려 (status → rejected)."""
    ok = get_store().reject_entry(entry_id)
    if not ok:
        raise HTTPException(
            status_code=404, detail=f"항목을 찾을 수 없습니다: {entry_id}"
        )
    entry = get_store().get_entry(entry_id)
    if entry is None:
        raise HTTPException(
            status_code=404, detail=f"항목을 찾을 수 없습니다: {entry_id}"
        )
    return entry


@router.get("/search")
def search_entries(
    q: str = Query(..., min_length=1),
    limit: int = Query(default=20, ge=1, le=200),
) -> list[dict[str, Any]]:
    """FTS5 전문 검색."""
    return get_store().search_entries(query=q, limit=limit)


@router.get("/stats")
def get_stats() -> dict[str, Any]:
    """카테고리별 / 상태별 통계."""
    return get_store().get_stats()


@router.post("/import")
def bulk_import(body: list[dict[str, Any]]) -> dict[str, Any]:
    """위키 항목 일괄 import."""
    count = get_store().bulk_import(body)
    return {"imported": count, "total": len(body)}
