"""Manual log — record off-watch sessions."""

from __future__ import annotations

from datetime import date

import pandas as pd
import streamlit as st

from openrun.web._helpers import get_conn, show_sidebar


st.set_page_config(page_title="Manual log · openrun", page_icon="📝", layout="wide")
show_sidebar()
st.title("📝 Manual log")
st.caption("Off-watch sessions (strength, hikes, unrecorded runs) — these feed the PMC when "
           "`include_manual=True` is the default for the dashboard.")

with st.form("manual_log", clear_on_submit=True):
    cols = st.columns(2)
    activity_date = cols[0].date_input("Date", value=date.today())
    activity_type = cols[1].selectbox(
        "Type",
        ["running", "trail_running", "strength", "hike", "cycling", "swim", "other"],
        index=2,
    )
    cols2 = st.columns(3)
    distance_km = cols2[0].number_input("Distance (km)", min_value=0.0, step=0.1, value=0.0)
    duration_min = cols2[1].number_input("Duration (min)", min_value=0, step=5, value=45)
    training_load = cols2[2].number_input("Training load", min_value=0.0, step=1.0, value=30.0)
    notes = st.text_input("Notes", placeholder="e.g. upper-body lift, morning hike")
    submitted = st.form_submit_button("Log session", type="primary")

if submitted:
    conn = get_conn()
    conn.execute(
        """INSERT INTO manual_activities
             (activity_date, activity_type, distance_km, duration_min,
              training_load, notes, source, imported_at)
           VALUES (?, ?, ?, ?, ?, ?, 'web', datetime('now'))""",
        (
            activity_date.isoformat(),
            activity_type,
            distance_km or None,
            duration_min or None,
            training_load or None,
            notes or None,
        ),
    )
    conn.commit()
    st.success(f"Logged {activity_type} on {activity_date.isoformat()}.")
    st.cache_data.clear()  # PMC etc. need to recompute

st.divider()
st.subheader("Recent manual entries")
rows = pd.read_sql(
    """SELECT activity_date, activity_type, distance_km, duration_min,
              training_load, notes, source
       FROM manual_activities
       ORDER BY activity_date DESC, id DESC
       LIMIT 50""",
    get_conn(),
)
if rows.empty:
    st.info("No manual sessions logged yet.")
else:
    st.dataframe(rows, width="stretch", hide_index=True)
