#!/usr/bin/env python3
"""Launch the ClaudeTimeline dashboard (start server + open browser).

Convenience wrapper around `scripts/serve start` that also verifies the
database exists and waits for the server to be reachable before opening
the browser.
"""

import subprocess
import sys
import urllib.error
import urllib.request
import webbrowser
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
DB_PATH = ROOT / "data" / "claude.db"
URL = "http://127.0.0.1:8000"
MAX_WAIT_SECONDS = 10
POLL_INTERVAL = 0.2


def _wait_for_server() -> bool:
    """Poll the server URL until it responds or timeout is reached.

    Returns True if the server responded, False on timeout.
    """
    import time

    deadline = time.monotonic() + MAX_WAIT_SECONDS
    while time.monotonic() < deadline:
        try:
            urllib.request.urlopen(URL, timeout=1)
            return True
        except (urllib.error.URLError, OSError):
            time.sleep(POLL_INTERVAL)
    return False


def main() -> None:
    # 1. Check database exists
    if not DB_PATH.exists():
        print(
            f"Database not found at {DB_PATH}\n"
            f"Run 'uv run scripts/build-db' first to build it.",
            file=sys.stderr,
        )
        sys.exit(1)

    # 2. Start server (handles frontend build check + idempotent start)
    result = subprocess.run(
        [sys.executable, str(ROOT / "scripts" / "serve"), "start"],
        check=False,
    )
    if result.returncode != 0:
        print("Failed to start server.", file=sys.stderr)
        sys.exit(result.returncode)

    # 3. Wait for server to be reachable
    if not _wait_for_server():
        print(
            f"Server did not become reachable at {URL} within {MAX_WAIT_SECONDS}s.\n"
            f"Check {ROOT / 'data' / 'server.log'} for errors.",
            file=sys.stderr,
        )
        sys.exit(1)

    # 4. Open browser
    webbrowser.open(URL)
    print(f"Dashboard opened at {URL}", file=sys.stderr)


if __name__ == "__main__":
    main()
