"""First-time setup wizard for planmyday."""

import os

from rich import print as rprint
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt

from ..application.config import get_config_dir, get_data_dir

console = Console()


class SetupWizard:
    """Interactive setup wizard for first-time users."""

    def __init__(self):
        self.config_dir = get_config_dir()
        self.data_dir = get_data_dir()
        self.env_file = self.config_dir / ".env"

    def run(self) -> bool:
        """
        Run the setup wizard.

        Returns:
            True if setup completed successfully, False otherwise.
        """
        self._show_welcome()

        # Step 1: Get API key
        api_key = self._prompt_api_key()
        if not api_key:
            rprint("\n[yellow]Setup cancelled.[/yellow]")
            return False

        # Step 2: Validate API key format
        if not self._validate_api_key_format(api_key):
            rprint("\n[red]Invalid API key format.[/red]")
            rprint("[dim]OpenAI API keys start with 'sk-' and are about 50 characters long.[/dim]")
            return False

        # Step 3: Create directories
        self._create_directories()

        # Step 4: Save API key
        self._save_api_key(api_key)

        # Step 5: Show success
        self._show_success()

        return True

    def _show_welcome(self) -> None:
        """Display welcome message."""
        welcome_text = """
[bold cyan]Welcome to planmyday![/bold cyan]

An AI-powered daily planning assistant that helps you create
realistic plans through conversational interaction.

This wizard will help you set up planmyday for first use.
"""
        panel = Panel(
            welcome_text.strip(),
            title="Setup Wizard",
            border_style="cyan",
        )
        console.print(panel)
        console.print()

    def _prompt_api_key(self) -> str | None:
        """Prompt user for OpenAI API key."""
        rprint("[bold]Step 1: OpenAI API Key[/bold]")
        rprint()
        rprint("planmyday uses OpenAI's GPT models to generate your daily plans.")
        rprint()
        rprint("[dim]Get your API key at: https://platform.openai.com/api-keys[/dim]")
        rprint()

        api_key = Prompt.ask(
            "Enter your OpenAI API key",
            password=True,  # Hide input
        )

        if not api_key or not api_key.strip():
            return None

        return api_key.strip()

    def _validate_api_key_format(self, api_key: str) -> bool:
        """Validate API key format (not connectivity)."""
        # OpenAI keys start with sk- and are typically 51 characters
        # But new project keys can have different formats
        if not api_key:
            return False

        # Basic format check: starts with sk- and reasonable length
        if api_key.startswith("sk-") and len(api_key) >= 20:
            return True

        # Also accept sk-proj- format (project-scoped keys)
        if api_key.startswith("sk-proj-") and len(api_key) >= 20:
            return True

        return False

    def _create_directories(self) -> None:
        """Create necessary directories."""
        rprint()
        rprint("[bold]Step 2: Creating directories[/bold]")
        rprint()

        directories = [
            self.config_dir,
            self.data_dir / "sessions",
            self.data_dir / "profiles",
            self.data_dir / "templates",
            self.data_dir / "exports" / "plans",
            self.data_dir / "exports" / "summaries",
        ]

        for directory in directories:
            directory.mkdir(parents=True, exist_ok=True)
            rprint(f"  [green]+[/green] {directory}")

    def _save_api_key(self, api_key: str) -> None:
        """Save API key to .env file."""
        rprint()
        rprint("[bold]Step 3: Saving configuration[/bold]")
        rprint()

        # Write .env file
        env_content = f"""# planmyday configuration
# Generated by 'pday setup'

OPENAI_API_KEY={api_key}
"""
        self.env_file.write_text(env_content)

        # Set restrictive permissions (owner read/write only)
        os.chmod(self.env_file, 0o600)

        rprint(f"  [green]+[/green] API key saved to {self.env_file}")
        rprint("  [dim](permissions: 600 - owner only)[/dim]")

    def _show_success(self) -> None:
        """Display success message with next steps."""
        success_text = f"""
[bold green]Setup complete![/bold green]

[bold]Configuration:[/bold]
  Config: {self.config_dir}
  Data:   {self.data_dir}

[bold]Next steps:[/bold]
  1. Create your first plan:  [cyan]pday start[/cyan]
  2. Set up your profile:     [cyan]pday profile[/cyan]
  3. Get help:                [cyan]pday --help[/cyan]

[dim]Tip: Use 'pday' for quick access, or 'planmyday' for the full command.[/dim]
"""
        console.print()
        panel = Panel(
            success_text.strip(),
            title="Ready to Go!",
            border_style="green",
        )
        console.print(panel)

    def is_configured(self) -> bool:
        """Check if planmyday is already configured."""
        return self.env_file.exists()

    def update_api_key(self) -> bool:
        """Update just the API key (not full setup)."""
        rprint("[bold]Update OpenAI API Key[/bold]")
        rprint()

        # Show current status
        if self.env_file.exists():
            rprint("[dim]Current key will be replaced.[/dim]")
            rprint()

        # Get new key
        api_key = self._prompt_api_key()
        if not api_key:
            rprint("\n[yellow]Cancelled.[/yellow]")
            return False

        # Validate
        if not self._validate_api_key_format(api_key):
            rprint("\n[red]Invalid API key format.[/red]")
            rprint("[dim]OpenAI API keys start with 'sk-' and are about 50 characters long.[/dim]")
            return False

        # Ensure config directory exists
        self.config_dir.mkdir(parents=True, exist_ok=True)

        # Save the key
        self._save_api_key(api_key)
        rprint("\n[green]API key updated successfully![/green]")
        return True

    def show_config_paths(self) -> None:
        """Display current configuration paths."""
        rprint(f"[bold]Config directory:[/bold] {self.config_dir}")
        rprint(f"[bold]Data directory:[/bold]   {self.data_dir}")
        rprint(f"[bold]Environment file:[/bold] {self.env_file}")

        if self.env_file.exists():
            rprint("\n[green]Status: Configured[/green]")
        else:
            rprint("\n[yellow]Status: Not configured[/yellow]")
            rprint("[dim]Run 'pday setup' to configure.[/dim]")
