"""Tracking Setup — FastAPI entry.

Slim entry point: creates the app, mounts static, includes routers, runs
startup hooks. Per-feature route logic lives in app/routes/*.py. Shared
dependencies (jinja env, auth helpers, audit, config) live in app/deps.py.

For the full plan see /srv/apps/tracking-setup/PLANNING.md.
"""

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

import auth
from db import execute, init_db, query_one
from deps import APP_BASE_URL, STATIC_DIR
from routes import auth_routes, clients, crawls, orgs, pages, reports

app = FastAPI(title="Tracking Setup", docs_url=None, redoc_url=None)

if STATIC_DIR.exists():
    app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")

app.include_router(pages.router)
app.include_router(auth_routes.router)
app.include_router(orgs.router)
app.include_router(clients.router)
app.include_router(crawls.router)
app.include_router(reports.router)


@app.on_event("startup")
def startup() -> None:
    init_db()
    _seed_first_admin()


def _seed_first_admin() -> None:
    """If no users exist, create a placeholder admin and log a one-time bootstrap link.

    The user opens the link, lands on /account/setup, sets their real email + password.
    """
    row = query_one("SELECT COUNT(*) AS n FROM user")
    if row and row["n"] > 0:
        return
    placeholder_id = execute(
        "INSERT INTO user (email, name, role) VALUES (?, ?, 'admin')",
        ("bootstrap@local", "Bootstrap"),
    )
    token = auth.issue_magic_link(placeholder_id)
    print(
        "================ BOOTSTRAP ADMIN ================\n"
        f"Visit: {APP_BASE_URL}/auth/bootstrap?token={token}\n"
        "Open this link to claim the admin account, set your real email + password.\n"
        "================================================="
    )
