"""
`skilark profile` command.

Shows the user's current profile (role, language, direction) and
offers options to edit individual fields or re-run the full profile flow.
Falls back to the profile migration screen for users who haven't set a profile.
"""

import logging

from InquirerPy import inquirer
from rich.console import Console

from skilark_cli.client import SkilarkClient
from skilark_cli.config_store import ConfigStore
from skilark_cli.onboarding import (
    DIRECTION_CHOICES,
    LANGUAGE_CHOICES,
    ROLE_CHOICES,
    derive_topics,
    run_profile_migration,
)

console = Console()
logger = logging.getLogger(__name__)


def _label_for(choices: list[dict], value: str) -> str:
    """Look up the display name for a value in a choices list."""
    return next((c["name"] for c in choices if c["value"] == value), value)


def run() -> None:
    """Show profile and offer edit options."""
    config_store = ConfigStore()

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

    config = config_store.load()

    if not config_store.has_profile():
        run_profile_migration(config_store, api_url=config["api_url"])
        return

    # Display current profile.
    role = config.get("current_role", "")
    language = config.get("primary_language", "")
    direction = config.get("career_direction", "")
    topics = config.get("topics", [])

    console.print()
    console.print("[bold]Your profile[/bold]")
    console.print(f"  Role:      {_label_for(ROLE_CHOICES, role)}")
    console.print(f"  Language:  {language}")
    console.print(f"  Direction: {_label_for(DIRECTION_CHOICES, direction)}")
    console.print(f"  Topics:    {', '.join(topics)}")
    console.print()

    action = inquirer.select(
        message="What would you like to do?",
        choices=[
            {"name": "Change role", "value": "role"},
            {"name": "Change language", "value": "language"},
            {"name": "Change direction", "value": "direction"},
            {"name": "My status", "value": "status"},
            {"name": "Link accounts", "value": "link"},
            {"name": "Back", "value": "back"},
        ],
    ).execute()

    if action == "back":
        return

    if action == "status":
        from skilark_cli.commands import status
        status.run()
        return

    if action == "link":
        from skilark_cli.commands import link
        link.dispatch([])
        return

    client = SkilarkClient(base_url=config["api_url"], user_id=config["user_id"])

    try:
        if action == "role":
            new_role = inquirer.select(
                message="What's your current role?",
                choices=ROLE_CHOICES,
                default=role,
            ).execute()
            new_topics = derive_topics(new_role, language)
            # API calls first — only persist locally if both succeed.
            client.update_profile(current_role=new_role)
            client.update_topics(new_topics)
            config_store.update_profile(current_role=new_role)
            config_store.update_topics(new_topics)
            console.print(f"\n[green]✓[/green] Role updated to {_label_for(ROLE_CHOICES, new_role)}.\n")

        elif action == "language":
            new_lang = inquirer.select(
                message="What's your primary programming language?",
                choices=LANGUAGE_CHOICES,
                default=language,
            ).execute()
            new_topics = derive_topics(role, new_lang)
            client.update_profile(primary_language=new_lang)
            client.update_topics(new_topics)
            config_store.update_profile(primary_language=new_lang)
            config_store.update_topics(new_topics)
            console.print(f"\n[green]✓[/green] Language updated to {new_lang}.\n")

        elif action == "direction":
            new_dir = inquirer.select(
                message="What's your career direction?",
                choices=DIRECTION_CHOICES,
                default=direction,
            ).execute()
            client.update_profile(career_direction=new_dir)
            config_store.update_profile(career_direction=new_dir)
            console.print(f"\n[green]✓[/green] Direction updated to {_label_for(DIRECTION_CHOICES, new_dir)}.\n")

    except Exception as exc:
        logger.debug("Profile update failed", exc_info=True)
        console.print(f"\n[red]Update failed:[/red] {exc}\n")
