"""Entry point for the skilark CLI."""

import sys

from skilark_cli import __version__


USAGE = """\
Usage: skilark [command]

Your career intelligence companion — daily challenges, job matching,
and market signals.

Running `skilark` with no arguments launches the full-screen terminal UI.

Commands:
  (default)       Launch the full-screen terminal UI
  today           Start your daily drill
  signals [--all] Show this week's market intelligence signals
  fit <query>     Find matching jobs by description or resume
  profile         View and edit your profile (includes status + link)
  feedback        Send feedback to the Skilark team
  menu            Interactive command menu

Options:
  --help, -h  Print this help message and exit
  --version   Print version and exit
"""

MENU_CHOICES = [
    {"name": "Daily drill", "value": "today"},
    {"name": "Market signals", "value": "signals"},
    {"name": "Find my fit", "value": "fit"},
    {"name": "My profile", "value": "profile"},
    {"name": "Send feedback", "value": "feedback"},
    {"name": "Quit", "value": "quit"},
]


def _show_menu() -> str:
    """Show interactive menu and return the chosen command value."""
    from InquirerPy import inquirer

    return inquirer.select(
        message="What would you like to do?",
        choices=MENU_CHOICES,
    ).execute()


def _prompt_fit_query() -> str | None:
    """Prompt user for a fit query. Returns None if empty."""
    from rich.prompt import Prompt

    query = Prompt.ask("Describe your ideal role").strip()
    return query or None


def _launch_tui(config_store) -> None:
    """Launch the full-screen TUI."""
    from skilark_cli.client import SkilarkClient
    from skilark_cli.tui.app import SkilarkApp

    config = config_store.load()
    client = SkilarkClient(
        base_url=config.get("api_url", "https://api.skilark.com"),
        user_id=config.get("user_id"),
    )
    app = SkilarkApp(
        client=client,
        topics=config.get("topics", []),
        coding_language=config.get("coding_language"),
        theme=config.get("theme"),
        config_store=config_store,
        code_cache_dir=config_store.config_dir,
    )
    app.run()



def _dispatch(command: str, rest: list[str]) -> None:
    """Route a command + remaining args to the appropriate handler."""
    if command == "today":
        from skilark_cli.commands import today
        today.run()
    elif command == "status":
        from skilark_cli.commands import status
        status.run()
    elif command == "profile":
        from skilark_cli.commands import profile
        profile.run()
    elif command == "config":
        from skilark_cli.commands import config
        config.run()
    elif command == "signals":
        from skilark_cli.commands import signals
        signals.dispatch(rest)
    elif command == "fit":
        from skilark_cli.commands import fit
        fit.dispatch(rest)
    elif command == "link":
        from skilark_cli.commands import link
        link.dispatch(rest)
    elif command == "feedback":
        from skilark_cli.commands import feedback
        feedback.run()
    elif command in ("tui", "menu"):
        if command == "menu":
            from skilark_cli.config_store import ConfigStore
            config_store = ConfigStore()
            if config_store.is_first_run():
                from skilark_cli.commands import today
                today.run()
                return
            choice = _show_menu()
            if choice == "quit":
                return
            if choice == "fit":
                query = _prompt_fit_query()
                if not query:
                    print("No query entered.")
                    return
                _dispatch("fit", [query])
                return
            _dispatch(choice, [])
            return
        from skilark_cli.config_store import ConfigStore
        config_store = ConfigStore()
        if config_store.is_first_run():
            from skilark_cli.commands import today
            today.run()
            return
        _launch_tui(config_store)
    else:
        print(f"Unknown command: {command!r}\n", file=sys.stderr)
        print(USAGE, file=sys.stderr)
        sys.exit(1)


def main() -> None:
    args = sys.argv[1:]

    if not args:
        from skilark_cli.config_store import ConfigStore

        config_store = ConfigStore()
        if config_store.is_first_run():
            from skilark_cli.commands import today
            today.run()
            return

        _launch_tui(config_store)
        return

    command = args[0]

    if command in ("--help", "-h", "help"):
        print(USAGE)
        return

    if command == "--version":
        print(f"skilark {__version__}")
        return

    _dispatch(command, args[1:])


if __name__ == "__main__":
    main()
