# retoor <retoor@molodetz.nl>

import logging

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse

from devplacepy.responses import respond
from devplacepy.schemas import AdminIssuesPlanningOut
from devplacepy.seo import base_seo_context
from devplacepy.services.gitea import runtime
from devplacepy.services.gitea.config import gitea_config
from devplacepy.services.gitea.planning import collect_open_issues
from devplacepy.utils import require_admin

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


async def _open_tickets() -> tuple[list[dict], bool]:
    try:
        issues = await collect_open_issues(runtime.get_client())
    except Exception as exc:
        logger.warning("Could not load open tickets for planning: %s", exc)
        return [], True
    tickets = [
        {
            "number": int(issue.get("number", 0)),
            "title": str(issue.get("title", "")).strip() or "Untitled",
            "labels": [
                str(label.get("name", "")).strip()
                for label in (issue.get("labels") or [])
                if isinstance(label, dict) and label.get("name")
            ],
        }
        for issue in issues
    ]
    return tickets, False


@router.get("/issues/planning", response_class=HTMLResponse)
async def admin_issues_planning(request: Request):
    admin = require_admin(request)
    seo_ctx = base_seo_context(
        request,
        title="Ticket Planning - Admin",
        description="Generate a grouped, ordered planning report of all open tickets.",
        robots="noindex,nofollow",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Admin", "url": "/admin"},
            {"name": "Issues", "url": "/issues"},
        ],
    )
    configured = gitea_config().is_configured
    tickets: list[dict] = []
    tickets_error = False
    if configured:
        tickets, tickets_error = await _open_tickets()
    context = {
        **seo_ctx,
        "request": request,
        "user": admin,
        "admin_section": "issues",
        "configured": configured,
        "tickets": tickets,
        "tickets_error": tickets_error,
    }
    return respond(request, "admin_issues_planning.html", context, model=AdminIssuesPlanningOut)
