import logging
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, JSONResponse
from devplacepy.templating import templates
from devplacepy.utils import require_admin
from devplacepy.services.manager import service_manager
from devplacepy.seo import base_seo_context, site_url, website_schema

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


@router.get("", response_class=HTMLResponse)
async def services_page(request: Request):
    admin = require_admin(request)
    services = service_manager.list_services()
    base = site_url(request)
    seo_ctx = base_seo_context(
        request,
        title="Services - Admin",
        description="Monitor background services on DevPlace.",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Admin", "url": "/admin"},
            {"name": "Services", "url": "/admin/services"},
        ],
        schemas=[website_schema(base)],
    )
    return templates.TemplateResponse(request, "services.html", {
        **seo_ctx,
        "request": request,
        "user": admin,
        "services": services,
        "admin_section": "services",
    })


@router.get("/data")
async def services_data(request: Request):
    require_admin(request)
    services = service_manager.list_services()
    return JSONResponse({"services": services})
