"""The first week.

The app grew a lot of surfaces — recordings, clips, the ingest tray, the
editor, settings, plugins, sharing, updates, a wall screen. Each one earned
its place, but a person opening this for the first time sees all of them at
once and no order to work in.

So there is one story, told in the order it actually happens: record a
session, get a chapter, make a clip, share it if you want to. Each step is
answered by real data rather than a checkbox someone ticks, which means it
cannot claim you have done something you have not — and it disappears for
good once the loop has been closed once.
"""
from fastapi import APIRouter

from clipshelf import config, db
from clipshelf.config import DATA

router = APIRouter(tags=["onboarding"])

DISMISSED = "onboarding_done"


def steps() -> list:
    conn = db.connect()
    try:
        vods = conn.execute("SELECT COUNT(*) n FROM vods").fetchone()["n"]
        chapters = conn.execute(
            "SELECT COUNT(*) n FROM vod_chapters").fetchone()["n"]
        marks = conn.execute(
            "SELECT COUNT(*) n FROM gsi_events WHERE event_type='bookmark'"
        ).fetchone()["n"]
    finally:
        conn.close()

    clips = 0
    try:
        from clipshelf import clips_api
        clips = len(clips_api.clips_saved(limit=1000)["clips"])
        shared = len(clips_api.share_index())
    except Exception:
        shared = 0

    return [
        {"key": "record",
         "title": "record a session",
         "done": vods > 0,
         "detail": f"{vods} recording{'' if vods == 1 else 's'} found" if vods
                   else "point the app at the folder OBS writes to, then record something",
         "where": "/settings.html#recording", "cta": "set the folder"},
        {"key": "chapter",
         "title": "let it find your games",
         "done": chapters > 0,
         "detail": f"{chapters} chapter{'' if chapters == 1 else 's'} on your timeline"
                   if chapters else
                   "play something while recording and it gets chaptered by itself — "
                   "or press the chapter hotkey to mark a segment yourself",
         "where": "/settings.html#hotkeys", "cta": "set a hotkey"},
        {"key": "clip",
         "title": "make a clip",
         "done": clips > 0,
         "detail": f"{clips} clip{'' if clips == 1 else 's'} saved" if clips else
                   ("press the clip hotkey while you play and trim it afterwards, "
                    f"or cut a range straight from the timeline"
                    + (f" — you have {marks} mark{'' if marks == 1 else 's'} waiting"
                       if marks else "")),
         "where": "/vods.html", "cta": "open a recording"},
        {"key": "share",
         "title": "share one (optional)",
         "done": shared > 0,
         "detail": f"{shared} clip{'' if shared == 1 else 's'} shared" if shared else
                   "publish with a link, or point it at your own domain",
         "where": "/settings.html#sharing", "cta": "set up sharing"},
    ]


@router.get("/api/onboarding")
def onboarding_state():
    st = steps()
    # the optional step does not hold the story open
    core_done = all(s["done"] for s in st if s["key"] != "share")
    return {"status": "success", "steps": st,
            "done": core_done,
            "dismissed": bool(config.CFG.get(DISMISSED)),
            "show": not (core_done or config.CFG.get(DISMISSED))}


@router.post("/api/onboarding/dismiss")
def onboarding_dismiss():
    config.CFG[DISMISSED] = True
    config.save(config.CFG)
    return onboarding_state()
