# retoor <retoor@molodetz.nl>

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from devplacepy.constants import TOPICS, TOPIC_LABELS
from devplacepy.database import get_table
from devplacepy.routers.feed import get_feed_posts, enrich_post_cards
from devplacepy.utils import get_current_user, not_found
from devplacepy.seo import list_page_seo, next_page_url
from devplacepy.responses import respond
from devplacepy.schemas import TopicOut, TopicsHubOut

router = APIRouter()


@router.get("", response_class=HTMLResponse)
async def topics_hub(request: Request):
    user = get_current_user(request)
    posts_table = get_table("posts")
    topics = [
        {
            "key": topic,
            "label": TOPIC_LABELS.get(topic, topic.title()),
            "post_count": posts_table.count(topic=topic, deleted_at=None),
        }
        for topic in TOPICS
    ]

    seo_ctx = list_page_seo(
        request,
        title="Topics",
        description="Browse DevPlace posts by topic: devlog, showcase, questions, rants, fun, and more.",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Topics", "url": "/topics"},
        ],
    )
    return respond(
        request,
        "topics.html",
        {
            **seo_ctx,
            "request": request,
            "user": user,
            "topics": topics,
        },
        model=TopicsHubOut,
    )


@router.get("/{topic}", response_class=HTMLResponse)
async def topic_page(request: Request, topic: str, before: str = None):
    if topic not in TOPICS:
        raise not_found("Topic not found")
    user = get_current_user(request)
    posts, next_cursor = get_feed_posts(user, "all", topic, "", before)
    posts = enrich_post_cards(posts, user)
    label = TOPIC_LABELS.get(topic, topic.title())

    seo_ctx = list_page_seo(
        request,
        title=f"{label} posts",
        description=f"Browse {label.lower()} posts from developers on DevPlace.",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Topics", "url": "/topics"},
            {"name": label, "url": f"/topics/{topic}"},
        ],
        next_url=next_page_url(request, next_cursor),
    )
    return respond(
        request,
        "topic.html",
        {
            **seo_ctx,
            "request": request,
            "user": user,
            "posts": posts,
            "topic": topic,
            "topic_label": label,
            "next_cursor": next_cursor,
        },
        model=TopicOut,
    )
