"""
Roura Agent Onboarding - First-run experience and guided setup.

This module provides:
- First-run detection via .env file
- Welcome screen with branding
- Tier comparison (FREE vs PRO)
- License key validation
- Provider configuration based on tier
- Automatic .env file creation

"""
from __future__ import annotations

import os
import sys
from pathlib import Path
from typing import Optional

from rich.console import Console
from rich.panel import Panel
from rich.prompt import Confirm, Prompt
from rich.table import Table

from .branding import BRAND_NAME, BRAND_TAGLINE, Colors, Icons, get_logo
from .licensing import Tier, clear_license_cache, get_current_tier, validate_license_key

# .env file location (current working directory)
ENV_FILE = Path.cwd() / ".env"

# Global .env in config directory (fallback)
GLOBAL_ENV_FILE = Path.home() / ".config" / "roura-agent" / ".env"

# Marker file to track if onboarding has been completed
ONBOARDING_MARKER = Path.home() / ".config" / "roura-agent" / ".onboarded"

# Marker file to track if walkthrough has been shown
WALKTHROUGH_MARKER = Path.home() / ".config" / "roura-agent" / ".walkthrough_seen"

# File to store last used provider
LAST_PROVIDER_FILE = Path.home() / ".config" / "roura-agent" / ".last_provider"

# Stripe payment URLs
STRIPE_URLS = {
    "pro_monthly": "https://buy.stripe.com/3cI28r8zl0tG92b6Cb5kk00",
    "pro_annual": "https://buy.stripe.com/14A7sL2aXa4g5PZ0dN5kk01",
    "pro_lifetime": "https://buy.stripe.com/4gMfZh8zl90c3HR3pZ5kk02",
}


def clear_screen() -> None:
    """Clear the terminal screen (only if running in a TTY)."""
    # Only clear screen if we're in an interactive terminal
    if sys.stdout.isatty():
        os.system('cls' if os.name == 'nt' else 'clear')


def get_env_file_path() -> Optional[Path]:
    """Get the path to the .env file if it exists."""
    if ENV_FILE.exists():
        return ENV_FILE
    if GLOBAL_ENV_FILE.exists():
        return GLOBAL_ENV_FILE
    return None


def is_first_run() -> bool:
    """Check if this is the first time running Roura Agent."""
    # Primary check: has onboarding been completed?
    if ONBOARDING_MARKER.exists():
        return False

    # Secondary check: does a .env file exist (created by our setup)?
    if get_env_file_path():
        return False

    return True


def mark_onboarding_complete() -> None:
    """Mark that onboarding has been completed."""
    ONBOARDING_MARKER.parent.mkdir(parents=True, exist_ok=True)
    ONBOARDING_MARKER.touch()


def is_walkthrough_seen() -> bool:
    """Check if the walkthrough has been shown before."""
    return WALKTHROUGH_MARKER.exists()


def mark_walkthrough_seen() -> None:
    """Mark that the walkthrough has been shown."""
    WALKTHROUGH_MARKER.parent.mkdir(parents=True, exist_ok=True)
    WALKTHROUGH_MARKER.touch()


def get_last_provider() -> Optional[str]:
    """Get the last used provider name."""
    if LAST_PROVIDER_FILE.exists():
        try:
            return LAST_PROVIDER_FILE.read_text().strip()
        except Exception:
            pass
    return None


def save_last_provider(provider: str) -> None:
    """Save the last used provider name."""
    LAST_PROVIDER_FILE.parent.mkdir(parents=True, exist_ok=True)
    LAST_PROVIDER_FILE.write_text(provider)


def load_env_file(path: Path) -> dict[str, str]:
    """Load environment variables from a .env file."""
    env_vars = {}
    if path.exists():
        for line in path.read_text().splitlines():
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                key, _, value = line.partition("=")
                # Remove quotes if present
                value = value.strip().strip('"').strip("'")
                env_vars[key.strip()] = value
    return env_vars


def save_env_file(path: Path, env_vars: dict[str, str]) -> None:
    """Save environment variables to a .env file."""
    path.parent.mkdir(parents=True, exist_ok=True)

    lines = [
        "# Roura Agent Configuration",
        "# Generated by roura-agent setup wizard",
        "",
    ]

    # Group variables
    groups = {
        "License": ["ROURA_LICENSE_KEY"],
        "Provider": ["ROURA_PROVIDER"],
        "Ollama": ["OLLAMA_BASE_URL", "OLLAMA_MODEL"],
        "OpenAI": ["OPENAI_API_KEY", "OPENAI_MODEL"],
        "Anthropic": ["ANTHROPIC_API_KEY", "ANTHROPIC_MODEL"],
    }

    for group_name, keys in groups.items():
        group_vars = {k: v for k, v in env_vars.items() if k in keys}
        if group_vars:
            lines.append(f"# {group_name}")
            for key in keys:
                if key in group_vars:
                    lines.append(f"{key}={group_vars[key]}")
            lines.append("")

    # Any remaining variables
    written_keys = set()
    for keys in groups.values():
        written_keys.update(keys)

    remaining = {k: v for k, v in env_vars.items() if k not in written_keys}
    if remaining:
        lines.append("# Other")
        for key, value in remaining.items():
            lines.append(f"{key}={value}")
        lines.append("")

    path.write_text("\n".join(lines))


def apply_env_file(path: Path) -> None:
    """Apply environment variables from .env file to current process."""
    env_vars = load_env_file(path)
    for key, value in env_vars.items():
        os.environ.setdefault(key, value)


def detect_ollama() -> tuple[bool, str, list[str]]:
    """
    Detect Ollama installation and available models.

    Returns:
        (is_available, base_url, models)
    """
    from .ollama import list_models

    # Try user-specified URL first, then localhost
    urls_to_try = ["http://localhost:11434"]

    for base_url in urls_to_try:
        try:
            models = list_models(base_url)
            return True, base_url, models
        except Exception:
            continue

    return False, "http://localhost:11434", []


def show_tier_comparison(console: Console) -> None:
    """Display FREE vs PRO tier comparison table."""
    table = Table(
        title="[bold]Choose Your Plan[/bold]",
        show_header=True,
        header_style="bold",
        border_style=Colors.BORDER_PRIMARY,
        title_justify="left",
    )

    table.add_column("Feature", style=Colors.DIM)
    table.add_column("FREE", justify="center", style=Colors.SUCCESS)
    table.add_column("PRO", justify="center", style=Colors.PRIMARY)

    # Features comparison
    features = [
        ("Local LLM (Ollama)", Icons.SUCCESS, Icons.SUCCESS),
        ("File Operations", Icons.SUCCESS, Icons.SUCCESS),
        ("Git Integration", Icons.SUCCESS, Icons.SUCCESS),
        ("Shell Commands", Icons.SUCCESS, Icons.SUCCESS),
        ("Session Persistence", Icons.SUCCESS, Icons.SUCCESS),
        ("", "", ""),
        ("OpenAI GPT-4", Icons.ERROR, Icons.SUCCESS),
        ("Anthropic Claude", Icons.ERROR, Icons.SUCCESS),
        ("Auto-fix Loops", Icons.ERROR, Icons.SUCCESS),
        ("GitHub Integration", Icons.ERROR, Icons.SUCCESS),
        ("Jira Integration", Icons.ERROR, Icons.SUCCESS),
        ("Priority Support", Icons.ERROR, Icons.SUCCESS),
    ]

    for feature, free_val, pro_val in features:
        if not feature:
            table.add_row("", "", "")
        else:
            free_display = f"[{Colors.SUCCESS}]{free_val}[/{Colors.SUCCESS}]" if free_val == Icons.SUCCESS else f"[{Colors.ERROR}]{free_val}[/{Colors.ERROR}]"
            pro_display = f"[{Colors.SUCCESS}]{pro_val}[/{Colors.SUCCESS}]"
            table.add_row(feature, free_display, pro_display)

    console.print(table)
    console.print()


def show_upgrade_links(console: Console) -> None:
    """Display Stripe upgrade links."""
    console.print(f"[{Colors.PRIMARY_BOLD}]Upgrade to PRO:[/{Colors.PRIMARY_BOLD}]")
    console.print()
    console.print(f"  [{Colors.SUCCESS}]Monthly[/{Colors.SUCCESS}]   $19/mo   {STRIPE_URLS['pro_monthly']}")
    console.print(f"  [{Colors.SUCCESS}]Annual[/{Colors.SUCCESS}]    $159/yr  {STRIPE_URLS['pro_annual']} [dim](save 30%)[/dim]")
    console.print(f"  [{Colors.SUCCESS}]Lifetime[/{Colors.SUCCESS}]  $299     {STRIPE_URLS['pro_lifetime']} [dim](one-time)[/dim]")
    console.print()


def get_recommended_models(available_models: list[str]) -> list[tuple[str, str]]:
    """
    Get recommended models from available models.

    Returns list of (model_name, reason) tuples.
    """
    recommendations = []

    # Priority models for coding tasks
    priority_models = [
        ("qwen2.5-coder", "Excellent for coding, fast tool calling"),
        ("qwen2.5", "Great general purpose with tool support"),
        ("llama3.1", "Meta's latest with tool calling"),
        ("llama3.2", "Efficient and capable"),
        ("deepseek-coder", "Strong coding model"),
        ("codellama", "Specialized for code"),
        ("mistral", "Fast and reliable"),
    ]

    # Match available models to priority list
    for model_prefix, reason in priority_models:
        matching = [m for m in available_models if m.startswith(model_prefix)]
        if matching:
            # Prefer larger variants
            matching.sort(key=lambda x: ("32b" in x, "14b" in x, "7b" in x), reverse=True)
            recommendations.append((matching[0], reason))

    # Add any remaining models not in recommendations
    recommended_names = {r[0] for r in recommendations}
    for model in available_models[:5]:
        if model not in recommended_names:
            recommendations.append((model, "Available on your system"))

    return recommendations[:5]


def run_onboarding(console: Optional[Console] = None) -> bool:
    """
    Run the first-run onboarding experience.

    Returns True if setup completed successfully, False otherwise.
    """
    console = console or Console()

    # Clear the terminal
    clear_screen()

    # Welcome screen
    console.print(get_logo())
    console.print()
    console.print(Panel(
        f"[{Colors.PRIMARY_BOLD}]Welcome to {BRAND_NAME}![/{Colors.PRIMARY_BOLD}]\n\n"
        f"{BRAND_TAGLINE}\n\n"
        f"Let's get you set up. This wizard will:\n"
        f"  {Icons.ARROW_RIGHT} Help you choose a plan (FREE or PRO)\n"
        f"  {Icons.ARROW_RIGHT} Configure your AI provider\n"
        f"  {Icons.ARROW_RIGHT} Create a .env file with your settings",
        title=f"[{Colors.PRIMARY}]{Icons.ROCKET} First-Time Setup[/{Colors.PRIMARY}]",
        border_style=Colors.BORDER_PRIMARY,
    ))
    console.print()

    # Environment variables to save
    env_vars: dict[str, str] = {}

    # Step 1: Show tier comparison
    console.print(f"[{Colors.PRIMARY_BOLD}]Step 1/3:[/{Colors.PRIMARY_BOLD}] Choose Your Plan\n")
    show_tier_comparison(console)
    show_upgrade_links(console)

    # Ask if they have a license key
    has_license = Confirm.ask(
        f"[{Colors.PRIMARY}]Do you have a license key?[/{Colors.PRIMARY}]",
        default=False,
    )

    tier = Tier.FREE

    if has_license:
        console.print()
        while True:
            license_key = Prompt.ask(
                f"[{Colors.PRIMARY}]Enter your license key[/{Colors.PRIMARY}]",
            )

            if not license_key.strip():
                console.print(f"[{Colors.WARNING}]Continuing with FREE tier.[/{Colors.WARNING}]")
                break

            # Validate license
            license_obj = validate_license_key(license_key.strip())
            if license_obj and license_obj.is_valid:
                tier = license_obj.tier
                env_vars["ROURA_LICENSE_KEY"] = license_key.strip()
                console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] License validated! Tier: [{Colors.PRIMARY_BOLD}]{tier.value.upper()}[/{Colors.PRIMARY_BOLD}]")
                break
            else:
                console.print(f"[{Colors.ERROR}]{Icons.ERROR}[/{Colors.ERROR}] Invalid license key. Please check and try again.")
                if not Confirm.ask("Try again?", default=True):
                    console.print(f"[{Colors.WARNING}]Continuing with FREE tier.[/{Colors.WARNING}]")
                    break

    console.print()

    # Step 2: Provider selection based on tier
    console.print(f"[{Colors.PRIMARY_BOLD}]Step 2/3:[/{Colors.PRIMARY_BOLD}] Configure AI Provider\n")

    if tier == Tier.FREE:
        console.print(f"[{Colors.DIM}]FREE tier uses Ollama for local AI inference.[/{Colors.DIM}]")
        console.print()

        # Step 1: Ask for Ollama URL first
        console.print(f"[{Colors.PRIMARY}]Enter your Ollama server URL:[/{Colors.PRIMARY}]")
        console.print(f"[{Colors.DIM}]Press Enter for default (localhost:11434)[/{Colors.DIM}]")
        console.print()

        ollama_url = Prompt.ask(
            "Ollama host:port",
            default="localhost:11434",
        )

        # Parse host:port and add http://
        ollama_url = ollama_url.strip()
        if not ollama_url.startswith("http"):
            ollama_url = f"http://{ollama_url}"
        env_vars["OLLAMA_BASE_URL"] = ollama_url

        # Step 2: Try to connect and fetch models
        console.print()
        console.print(f"[{Colors.DIM}]Connecting to {ollama_url}...[/{Colors.DIM}]")

        from .ollama import list_models
        models = []
        try:
            models = list_models(ollama_url)
            console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] Connected! Found {len(models)} model(s)")
        except Exception as e:
            console.print(f"[{Colors.WARNING}]{Icons.WARNING}[/{Colors.WARNING}] Could not connect: {e}")
            console.print()
            console.print(Panel(
                f"[{Colors.WARNING}]Ollama not reachable at {ollama_url}[/{Colors.WARNING}]\n\n"
                "Make sure Ollama is installed and running:\n\n"
                f"[{Colors.PRIMARY}]To install:[/{Colors.PRIMARY}]\n"
                "  macOS/Linux: curl -fsSL https://ollama.com/install.sh | sh\n"
                "  Windows:     Download from https://ollama.com/download\n\n"
                "To start Ollama:\n"
                "  ollama serve\n\n"
                "To pull a model:\n"
                "  ollama pull qwen2.5-coder:7b",
                border_style=Colors.BORDER_WARNING,
            ))

        # Step 3: Model selection
        console.print()
        if models:
            recommendations = get_recommended_models(models)

            table = Table(title="Available Models", show_header=True)
            table.add_column("#", style=Colors.DIM, width=3)
            table.add_column("Model", style=Colors.PRIMARY)
            table.add_column("Notes", style=Colors.DIM)

            for i, (model, reason) in enumerate(recommendations, 1):
                marker = " (Recommended)" if i == 1 else ""
                table.add_row(str(i), f"{model}{marker}", reason)

            console.print(table)
            console.print()

            while True:
                choice = Prompt.ask(
                    "Select model number or enter model name",
                    default="1",
                )

                if choice.isdigit() and 1 <= int(choice) <= len(recommendations):
                    model_name = recommendations[int(choice) - 1][0]
                    break
                elif choice in models:
                    model_name = choice
                    break
                elif any(m.startswith(choice) for m in models):
                    matches = [m for m in models if m.startswith(choice)]
                    model_name = matches[0]
                    break
                else:
                    console.print(f"[{Colors.WARNING}]Invalid selection. Try again.[/{Colors.WARNING}]")

            env_vars["OLLAMA_MODEL"] = model_name
            console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] Selected model: {model_name}")
        else:
            console.print(f"[{Colors.DIM}]No models available. Enter a model name to use:[/{Colors.DIM}]")
            console.print(f"[{Colors.DIM}]Pull models with: ollama pull qwen2.5-coder:7b[/{Colors.DIM}]")
            console.print()
            model_name = Prompt.ask(
                "Model name",
                default="qwen2.5-coder:7b",
            )
            env_vars["OLLAMA_MODEL"] = model_name
            console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] Will use model: {model_name}")

        env_vars["ROURA_PROVIDER"] = "ollama"

    else:
        # PRO or ENTERPRISE tier - can use cloud providers
        console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] {tier.value.upper()} tier unlocks cloud providers!")
        console.print()
        console.print(f"[{Colors.DIM}]You can configure multiple providers and switch between them later.[/{Colors.DIM}]")
        console.print()

        # Step 2a: Choose default provider
        providers = [
            ("1", "Ollama", "Local inference (free, private)"),
            ("2", "OpenAI", "GPT-4, GPT-4-turbo"),
            ("3", "Anthropic", "Claude 3.5 Sonnet"),
        ]

        table = Table(title="Choose Default Provider", show_header=True)
        table.add_column("#", style=Colors.DIM, width=3)
        table.add_column("Provider", style=Colors.PRIMARY)
        table.add_column("Description", style=Colors.DIM)

        for num, name, desc in providers:
            table.add_row(num, name, desc)

        console.print(table)
        console.print()

        provider_choice = Prompt.ask(
            "Select default provider",
            choices=["1", "2", "3"],
            default="1",
        )

        # Configure selected provider
        if provider_choice == "1":
            env_vars["ROURA_PROVIDER"] = "ollama"
        elif provider_choice == "2":
            env_vars["ROURA_PROVIDER"] = "openai"
        elif provider_choice == "3":
            env_vars["ROURA_PROVIDER"] = "anthropic"

        console.print()

        # Step 2b: Configure Ollama (always available)
        console.print(f"[{Colors.PRIMARY_BOLD}]Configure Ollama[/{Colors.PRIMARY_BOLD}] [dim](local, always available)[/dim]")
        console.print()

        ollama_url = Prompt.ask(
            "Ollama host:port",
            default="localhost:11434",
        )
        ollama_url = ollama_url.strip()
        if not ollama_url.startswith("http"):
            ollama_url = f"http://{ollama_url}"
        env_vars["OLLAMA_BASE_URL"] = ollama_url

        from .ollama import list_models
        models = []
        try:
            models = list_models(ollama_url)
            console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] Connected, found {len(models)} model(s)")
        except Exception:
            console.print(f"[{Colors.DIM}]Ollama not running - can configure later[/{Colors.DIM}]")

        if models:
            recommendations = get_recommended_models(models)
            console.print(f"[{Colors.DIM}]Available: {', '.join(m for m, _ in recommendations[:3])}[/{Colors.DIM}]")
            model_name = Prompt.ask("Ollama model", default=recommendations[0][0] if recommendations else "qwen2.5-coder:7b")
        else:
            model_name = Prompt.ask("Ollama model", default="qwen2.5-coder:7b")
        env_vars["OLLAMA_MODEL"] = model_name

        console.print()

        # Step 2c: Configure OpenAI (optional)
        console.print(f"[{Colors.PRIMARY_BOLD}]Configure OpenAI[/{Colors.PRIMARY_BOLD}] [dim](optional)[/dim]")
        if Confirm.ask("Add OpenAI API key?", default=provider_choice == "2"):
            api_key = Prompt.ask(
                "OpenAI API key",
                password=True,
            )
            if api_key.strip():
                env_vars["OPENAI_API_KEY"] = api_key.strip()
                env_vars["OPENAI_MODEL"] = Prompt.ask(
                    "OpenAI model",
                    default="gpt-4-turbo-preview",
                )
                console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] OpenAI configured")
        console.print()

        # Step 2d: Configure Anthropic (optional)
        console.print(f"[{Colors.PRIMARY_BOLD}]Configure Anthropic[/{Colors.PRIMARY_BOLD}] [dim](optional)[/dim]")
        if Confirm.ask("Add Anthropic API key?", default=provider_choice == "3"):
            api_key = Prompt.ask(
                "Anthropic API key",
                password=True,
            )
            if api_key.strip():
                env_vars["ANTHROPIC_API_KEY"] = api_key.strip()
                env_vars["ANTHROPIC_MODEL"] = Prompt.ask(
                    "Anthropic model",
                    default="claude-3-5-sonnet-20241022",
                )
                console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] Anthropic configured")

        console.print()

        # Step 2e: Configure Jira (optional, PRO only)
        console.print(f"[{Colors.PRIMARY_BOLD}]Configure Jira[/{Colors.PRIMARY_BOLD}] [dim](optional)[/dim]")
        if Confirm.ask("Set up Jira integration?", default=False):
            console.print(f"[{Colors.DIM}]Get your API token from: https://id.atlassian.com/manage-profile/security/api-tokens[/{Colors.DIM}]")
            console.print()

            jira_url = Prompt.ask("Jira URL (e.g., https://company.atlassian.net)")
            if jira_url.strip():
                env_vars["JIRA_URL"] = jira_url.strip().rstrip("/")

                jira_email = Prompt.ask("Jira email")
                if jira_email.strip():
                    env_vars["JIRA_EMAIL"] = jira_email.strip()

                    jira_token = Prompt.ask("Jira API token", password=True)
                    if jira_token.strip():
                        env_vars["JIRA_TOKEN"] = jira_token.strip()
                        console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] Jira configured")

        console.print()

        # Step 2f: Check GitHub CLI (optional, PRO only)
        console.print(f"[{Colors.PRIMARY_BOLD}]GitHub Integration[/{Colors.PRIMARY_BOLD}] [dim](uses gh CLI)[/dim]")
        console.print()

        # Check if gh is installed and authenticated
        import subprocess
        try:
            result = subprocess.run(
                ["gh", "auth", "status"],
                capture_output=True,
                text=True,
                timeout=10,
            )
            if result.returncode == 0:
                console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] GitHub CLI authenticated")
                # Extract account info
                for line in result.stderr.split("\n"):
                    if "Logged in to" in line:
                        console.print(f"[{Colors.DIM}]   {line.strip()}[/{Colors.DIM}]")
                        break
            else:
                console.print(f"[{Colors.WARNING}]{Icons.WARNING}[/{Colors.WARNING}] GitHub CLI not authenticated")
                console.print(f"[{Colors.DIM}]   Run: gh auth login[/{Colors.DIM}]")
        except FileNotFoundError:
            console.print(f"[{Colors.WARNING}]{Icons.WARNING}[/{Colors.WARNING}] GitHub CLI not installed")
            console.print(f"[{Colors.DIM}]   Install: brew install gh[/{Colors.DIM}]")
        except Exception:
            console.print(f"[{Colors.DIM}]GitHub CLI check skipped[/{Colors.DIM}]")

    console.print()

    # Step 3: Save configuration
    console.print(f"[{Colors.PRIMARY_BOLD}]Step 3/3:[/{Colors.PRIMARY_BOLD}] Save Configuration\n")

    # Determine where to save
    save_global = Confirm.ask(
        "Save to global config (~/.config/roura-agent/.env)? (No = save to current directory)",
        default=True,
    )

    env_path = GLOBAL_ENV_FILE if save_global else ENV_FILE
    save_env_file(env_path, env_vars)

    console.print(f"[{Colors.SUCCESS}]{Icons.SUCCESS}[/{Colors.SUCCESS}] Configuration saved to {env_path}")

    # Apply to current process
    for key, value in env_vars.items():
        os.environ[key] = value

    # Clear license cache to pick up new key
    clear_license_cache()

    console.print()

    # Show completion message
    tier_display = get_current_tier()
    console.print(Panel(
        f"[{Colors.PRIMARY_BOLD}]Setup Complete![/{Colors.PRIMARY_BOLD}]\n\n"
        f"Tier: [{Colors.SUCCESS}]{tier_display.value.upper()}[/{Colors.SUCCESS}]\n"
        f"Provider: [{Colors.PRIMARY}]{env_vars.get('ROURA_PROVIDER', 'ollama')}[/{Colors.PRIMARY}]\n\n"
        f"[{Colors.PRIMARY}]Quick start:[/{Colors.PRIMARY}]\n"
        "  - Type your request and press Enter\n"
        "  - I can read, write, and edit files\n"
        "  - I'll ask for approval before changes\n"
        "  - Press Ctrl+C to interrupt\n\n"
        f"[{Colors.DIM}]Configuration: {env_path}[/{Colors.DIM}]",
        title=f"[{Colors.SUCCESS}]{Icons.SUCCESS} Ready![/{Colors.SUCCESS}]",
        border_style=Colors.BORDER_SUCCESS,
    ))

    # Mark onboarding as complete
    mark_onboarding_complete()

    return True


def check_and_run_onboarding(console: Optional[Console] = None) -> bool:
    """
    Check if onboarding is needed and run it if so.

    Returns True if ready to proceed, False if setup incomplete.
    """
    # Always apply existing .env file if present
    env_path = get_env_file_path()
    if env_path:
        apply_env_file(env_path)

    if is_first_run():
        return run_onboarding(console)

    return True


def get_tier_display() -> str:
    """Get a formatted string showing the current tier for the UI."""
    tier = get_current_tier()

    if tier == Tier.ENTERPRISE:
        return f"[bold magenta]{Icons.KEY} ENTERPRISE[/bold magenta]"
    elif tier == Tier.PRO:
        return f"[bold cyan]{Icons.KEY} PRO[/bold cyan]"
    else:
        return f"[dim]{Icons.KEY} FREE[/dim]"
