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

from app.database import get_db
from online_dev.page_manager.service import PageService, PageServiceException

router = APIRouter(prefix="/page", tags=["page-render"])


def _format_datetime(dt) -> str:
    return dt.strftime("%Y-%m-%d %H:%M:%S") if dt else ""


def _build_page_out(page) -> dict:
    return {
        "id": str(page.id),
        "application_id": page.application_id,
        "name": page.name,
        "code": page.code,
        "category": page.category or "",
        "description": page.description or "",
        "status": page.status,
        "version": page.version,
        "page_config": page.page_config or {},
        "sort": page.sort or 0,
        "sys_create_datetime": _format_datetime(page.sys_create_datetime),
        "sys_update_datetime": _format_datetime(page.sys_update_datetime),
    }


@router.get("/code/{code}", summary="Get page config by code")
async def get_page_by_code(code: str, db: AsyncSession = Depends(get_db)):
    try:
        page = await PageService.get_by_code(db, code)
        return _build_page_out(page)
    except PageServiceException as e:
        raise HTTPException(status_code=400, detail=str(e)) from e
