"""Topical Tags view."""

from __future__ import annotations

from sqlalchemy import select
from starlette.requests import Request
from starlette.responses import Response

from fenliu.config import settings
from fenliu.database import get_db
from fenliu.models import TopicalHashtag
from fenliu.services.api_key import get_api_key
from fenliu.templates_env import templates
from fenliu.utils.display import process_topical_tag_for_display


async def topical_tags_page(request: Request) -> Response:
    """Render the topical hashtag rules management page."""
    with get_db() as db:
        stmt = select(TopicalHashtag).order_by(TopicalHashtag.created_at.desc())
        result = db.execute(stmt)
        tags = list(result.scalars().all())

        processed_tags = [process_topical_tag_for_display(tag) for tag in tags]

        api_key = get_api_key(db)

        context = {
            "tags": processed_tags,
            "app_name": settings.app_name,
            "app_version": settings.app_version,
            "api_key": api_key or "",
        }
        return templates.TemplateResponse(request, "topical_tags.html", context)
