# retoor <retoor@molodetz.nl>

from fastapi import Request

from devplacepy.responses import json_error, wants_json
from devplacepy.templating import templates
from devplacepy.seo import base_seo_context, site_url, website_schema
from devplacepy.services.gitea.client import STATE_ALL, STATE_CLOSED, STATE_OPEN

PER_PAGE = 20
VALID_STATES = (STATE_OPEN, STATE_CLOSED, STATE_ALL)


def state_or_default(raw: str) -> str:
    return raw if raw in VALID_STATES else STATE_OPEN


def author_fields(author_uid: str | None, users_map: dict, fallback_login: str) -> dict:
    user = users_map.get(author_uid) if author_uid else None
    if user:
        return {
            "author_username": user["username"],
            "author_uid": author_uid,
            "author_avatar_seed": user.get("avatar_seed") or user["username"],
            "is_local_author": True,
        }
    return {
        "author_username": fallback_login or "developer",
        "author_uid": None,
        "author_avatar_seed": None,
        "is_local_author": False,
    }


def issue_item(issue: dict, author_uid: str | None, users_map: dict) -> dict:
    login = (issue.get("user") or {}).get("login", "")
    return {
        "number": int(issue.get("number", 0)),
        "title": issue.get("title", ""),
        "state": issue.get("state", "open"),
        "html_url": issue.get("html_url"),
        "comments_count": int(issue.get("comments", 0)),
        "created_at": issue.get("created_at"),
        "updated_at": issue.get("updated_at"),
        **author_fields(author_uid, users_map, login),
    }


def comment_item(comment: dict, author_uid: str | None, users_map: dict) -> dict:
    login = (comment.get("user") or {}).get("login", "")
    return {
        "id": int(comment.get("id", 0)),
        "body": comment.get("body", ""),
        "html_url": comment.get("html_url"),
        "created_at": comment.get("created_at"),
        **author_fields(author_uid, users_map, login),
    }


def issue_seo(request: Request, **extra) -> dict:
    base = site_url(request)
    return base_seo_context(
        request,
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Issue Reports", "url": "/issues"},
        ],
        schemas=[website_schema(base)],
        **extra,
    )


def tracker_unavailable(request: Request):
    if wants_json(request):
        return json_error(503, "The issue tracker is temporarily unavailable")
    seo_ctx = base_seo_context(
        request,
        title="Issue tracker unavailable - DevPlace",
        description="The issue tracker is temporarily unavailable.",
        robots="noindex",
    )
    return templates.TemplateResponse(
        request,
        "error.html",
        {
            **seo_ctx,
            "request": request,
            "error_code": 503,
            "error_message": "The issue tracker is temporarily unavailable.",
        },
        status_code=503,
    )
