import asyncio
from contextlib import asynccontextmanager

from starlette.staticfiles import StaticFiles
from markupsafe import Markup
from pyview import PyView
from pyview.template import defaultRootTemplate
from .data.session_store import get_index
from .views import SessionListView, SessionDetailView


@asynccontextmanager
async def lifespan(app):
    asyncio.create_task(asyncio.to_thread(get_index().load))
    yield


app = PyView(lifespan=lifespan)
app.mount("/static", StaticFiles(packages=[("pyview", "static")]), name="static")
app.mount("/app-static", StaticFiles(packages=[("agent_devlog", "static")]), name="app-static")

app_head = Markup("""
    <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700&family=DM+Sans:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="/app-static/styles.css">
""")

app.rootTemplate = defaultRootTemplate(css=app_head, title="Agent DevLog")

routes = [
    ("/", SessionListView),
    ("/sessions/{project_dir}/{session_id}", SessionDetailView),
]

for path, view in routes:
    app.add_live_view(path, view)
