"""FastAPI + HTMX dashboard for browsing Claude Code session transcripts."""

from __future__ import annotations

from contextlib import asynccontextmanager
from pathlib import Path
from typing import TYPE_CHECKING

from fastapi import FastAPI

from blackbox.dashboard.routes import PROJECTS_DIR, router
from blackbox.dashboard.watcher import SessionWatcher

if TYPE_CHECKING:
    from collections.abc import AsyncIterator


def create_app(projects_dir: Path | None = None) -> FastAPI:
    """Create the dashboard FastAPI app, optionally overriding the projects directory."""
    actual_dir = projects_dir or PROJECTS_DIR

    @asynccontextmanager
    async def lifespan(the_app: FastAPI) -> AsyncIterator[None]:
        """Start/stop the session watcher around the app lifecycle."""
        watcher = SessionWatcher(actual_dir)
        watcher.start()
        the_app.state.watcher = watcher
        the_app.state.projects_dir = actual_dir
        yield
        watcher.stop()

    application = FastAPI(title="blackbox", lifespan=lifespan)
    application.include_router(router)
    return application


app = create_app()
