"""Streams 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 HashtagStream
from fenliu.services.api_key import get_api_key
from fenliu.templates_env import templates
from fenliu.utils.display import process_stream_for_display


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

        # Process streams using helper function
        processed_streams = [process_stream_for_display(stream) for stream in streams]

        # Get API key if it exists
        api_key = get_api_key(db)

        context = {
            "streams": processed_streams,
            "app_name": settings.app_name,
            "app_version": settings.app_version,
            "default_instance": settings.default_instance,
            "api_key": api_key or "",
        }
        return templates.TemplateResponse(request, "hashtag_streams.html", context)
