"""
`skilark config` command.

Allows the user to interactively update their topic preferences.
Presents a pre-populated checkbox prompt showing current selections,
then persists any changes to the config file on disk.
Exits early with a friendly message if the user has not yet run setup.
"""

from InquirerPy import inquirer
from rich.console import Console

from skilark_cli.config_store import ConfigStore
from skilark_cli.onboarding import TOPIC_CHOICES

console = Console()


def run() -> None:
    """Interactively update the user's topic preferences."""
    config_store = ConfigStore()

    if config_store.is_first_run():
        console.print("[dim]Run 'skilark today' first to get started.[/dim]")
        return

    config = config_store.load()
    current_topics = set(config.get("topics", []))

    console.print(f"\n[bold]Current topics:[/bold] {', '.join(sorted(current_topics))}\n")

    choices = [
        {"name": t["name"], "value": t["value"], "enabled": t["value"] in current_topics}
        for t in TOPIC_CHOICES
    ]

    selected = inquirer.checkbox(
        message="Update topics (space to toggle, enter to confirm):",
        choices=choices,
        validate=lambda result: len(result) >= 1,
        invalid_message="Pick at least one topic.",
    ).execute()

    config_store.update_topics(selected)

    added = set(selected) - current_topics
    removed = current_topics - set(selected)
    if added:
        console.print(f"[green]+ Added:[/green] {', '.join(sorted(added))}")
    if removed:
        console.print(f"[red]- Removed:[/red] {', '.join(sorted(removed))}")
    if not added and not removed:
        console.print("[dim]No changes.[/dim]")
    console.print()
