"""
Wiki.js Integration API Router (read-only)
"""

import logging
from typing import Optional

from fastapi import APIRouter, HTTPException, Query

from app.core.config import settings
from app.core.database import execute_query_single
from app.modules.wiki.backend.service import WikiService
from app.modules.wiki.models.schemas import WikiPageResponse

logger = logging.getLogger(__name__)
router = APIRouter()
service = WikiService()


@router.get("/customers/{customer_id}/pages", response_model=WikiPageResponse)
async def list_customer_wiki_pages(
    customer_id: int,
    tag: Optional[str] = Query(None),
    query: Optional[str] = Query(None),
    limit: int = Query(20, ge=1, le=100),
):
    customer = execute_query_single(
        "SELECT id, name, wiki_slug FROM customers WHERE id = %s",
        (customer_id,),
    )
    if not customer:
        raise HTTPException(status_code=404, detail="Customer not found")

    wiki_slug = (customer.get("wiki_slug") or "").strip()
    effective_tag = tag
    if not effective_tag and not (query or "").strip():
        effective_tag = "guide"

    if not wiki_slug:
        return WikiPageResponse(
            pages=[],
            path="/en/Kunder",
            tag=effective_tag,
            query=query,
            base_url=settings.WIKI_BASE_URL,
        )

    payload = await service.list_customer_pages(
        slug=wiki_slug,
        tag=effective_tag,
        query=query,
        limit=limit,
    )
    return WikiPageResponse(**payload)
