"""openrun — Streamlit controller.

Uses `st.navigation` to build the sidebar from an explicit page list. This
lets us hide Welcome after first-run setup completes — directory-based
auto-discovery (the older Streamlit pattern) would show every file in
`pages/` no matter what.

Pages are grouped into thematic sections so the sidebar stays scannable.
`Activity detail` is registered but tucked under `Activities` since it's
only reached via clickthrough from the Activities list.
"""

from __future__ import annotations

import streamlit as st

from openrun.config import _find_config
from openrun.web._helpers import get_conn


st.set_page_config(
    page_title="openrun",
    page_icon="🏃",
    layout="wide",
    initial_sidebar_state="expanded",
)


# ---------------------------------------------------------------------------
# First-run detection
# ---------------------------------------------------------------------------

def _is_first_run() -> bool:
    if _find_config() is None:
        return True
    try:
        n = get_conn().execute("SELECT COUNT(*) FROM activities").fetchone()[0]
    except Exception:  # noqa: BLE001
        return True
    return n == 0


needs_setup = _is_first_run() or st.session_state.get("show_welcome", False)


# ---------------------------------------------------------------------------
# Page registry — Streamlit resolves these paths relative to this entrypoint.
# ---------------------------------------------------------------------------

home            = st.Page("pages/Home.py",              title="Home",            icon="🏠", default=True)
dashboard       = st.Page("pages/1_Dashboard.py",       title="Dashboard",       icon="📊")
activities      = st.Page("pages/2_Activities.py",      title="Activities",      icon="📋")
activity_detail = st.Page("pages/8_Activity_Detail.py", title="Activity detail", icon="🏃")
race_plan       = st.Page("pages/3_Race_Plan.py",       title="Race plan",       icon="📈")
manual_log      = st.Page("pages/4_Manual_Log.py",      title="Manual log",      icon="📝")
recovery        = st.Page("pages/6_Recovery.py",        title="Recovery",        icon="🛌")
efficiency      = st.Page("pages/7_Efficiency.py",      title="Efficiency",      icon="🫀")
sync_page       = st.Page("pages/5_Sync.py",            title="Sync",            icon="🔄")
welcome         = st.Page("pages/0_Welcome.py",         title="Setup",           icon="👋")

sections = {
    "": [home, dashboard],
    "Train": [activities, activity_detail, race_plan, manual_log],
    "Insight": [recovery, efficiency],
    "Data": [sync_page],
}
if needs_setup:
    sections["Setup"] = [welcome]

st.navigation(sections).run()
