"""CLI commands — onboard_cmd."""

import asyncio
import os
import platform
import shutil
import subprocess
import sys
from pathlib import Path

import typer
from rich.console import Console
from rich.table import Table

from flowly import __version__, __logo__

console = Console()

# ============================================================================
# Onboard / Setup
# ============================================================================


def onboard():
    """Initialize flowly configuration and workspace."""
    from flowly.config.loader import get_config_path, save_config
    from flowly.config.schema import Config
    from flowly.utils.helpers import get_workspace_path

    config_path = get_config_path()

    if config_path.exists():
        console.print(f"[yellow]Config already exists at {config_path}[/yellow]")
        if not typer.confirm("Overwrite?"):
            raise typer.Exit()

    # Create default config
    config = Config()
    save_config(config)
    console.print(f"[green]✓[/green] Created config at {config_path}")

    # Create workspace
    workspace = get_workspace_path()
    console.print(f"[green]✓[/green] Created workspace at {workspace}")

    # Create default bootstrap files
    _create_workspace_templates(workspace)

    # Copy builtin persona files to workspace
    _install_persona_files(workspace)

    # Persona selection
    console.print("\n[bold cyan]Choose a persona for your bot:[/bold cyan]")
    personas_dir = workspace / "personas"
    if personas_dir.exists():
        choices = [f.stem for f in sorted(personas_dir.glob("*.md"))]
        for i, name in enumerate(choices, 1):
            marker = " [green](default)[/green]" if name == "default" else ""
            console.print(f"  {i}. [cyan]{name}[/cyan]{marker}")
        choice = typer.prompt("Select persona number", default="1")
        try:
            idx = int(choice) - 1
            if 0 <= idx < len(choices):
                selected = choices[idx]
                config.agents.defaults.persona = selected
                save_config(config)
                console.print(f"[green]✓[/green] Persona set to: [cyan]{selected}[/cyan]")
            else:
                console.print("[dim]Using default persona.[/dim]")
        except ValueError:
            console.print("[dim]Using default persona.[/dim]")

    console.print(f"\n{__logo__} flowly is ready!")
    console.print("\nNext steps:")
    console.print("  1. Add your API key to [cyan]~/.flowly/config.json[/cyan]")
    console.print("     Get one at: https://openrouter.ai/keys")
    console.print("  2. Chat: [cyan]flowly agent -m \"Hello!\"[/cyan]")
    console.print("\n[dim]Want Telegram/WhatsApp? Run: flowly channels login[/dim]")
    console.print("[dim]Change persona later: flowly persona set <name>[/dim]")




def _create_workspace_templates(workspace: Path):
    """Create default workspace template files."""
    # Load templates from the package's workspace/ directory so edits there propagate automatically
    builtin_workspace = Path(__file__).parent.parent.parent / "workspace"

    default_templates: dict[str, str] = {
        "AGENTS.md": (
            "# Agent Instructions\n\n"
            "You are a helpful AI assistant. Be concise, accurate, and friendly.\n\n"
            "## Guidelines\n\n"
            "- Always explain what you're doing before taking actions\n"
            "- Ask for clarification when the request is ambiguous\n"
            "- Use tools to help accomplish tasks\n"
            "- Remember important information in your memory files\n"
        ),
        "SOUL.md": "",
        "USER.md": "",
    }

    for filename, fallback in default_templates.items():
        file_path = workspace / filename
        if file_path.exists():
            continue
        # Try to load from package workspace first
        src = builtin_workspace / filename
        content = src.read_text(encoding="utf-8") if src.exists() else fallback
        file_path.write_text(content, encoding="utf-8")
        console.print(f"  [dim]Created {filename}[/dim]")

    # Create memory directory and MEMORY.md
    memory_dir = workspace / "memory"
    memory_dir.mkdir(exist_ok=True)
    memory_file = memory_dir / "MEMORY.md"
    if not memory_file.exists():
        memory_file.write_text("""# Long-term Memory

This file stores important information that should persist across sessions.

## User Information

(Important facts about the user)

## Preferences

(User preferences learned over time)

## Important Notes

(Things to remember)
""", encoding="utf-8")
        console.print("  [dim]Created memory/MEMORY.md[/dim]")


def _install_persona_files(workspace: Path):
    """Copy builtin persona files to workspace/personas/ directory."""
    personas_dir = workspace / "personas"
    personas_dir.mkdir(exist_ok=True)

    # Builtin personas are shipped in the package's workspace/personas/ directory
    builtin_dir = Path(__file__).parent.parent.parent / "workspace" / "personas"
    if builtin_dir.exists():
        for src in builtin_dir.glob("*.md"):
            dst = personas_dir / src.name
            if not dst.exists():
                dst.write_text(src.read_text(encoding="utf-8"), encoding="utf-8")
                console.print(f"  [dim]Created personas/{src.name}[/dim]")
    else:
        # Fallback: create a minimal default persona
        default_file = personas_dir / "default.md"
        if not default_file.exists():
            default_file.write_text(
                "# Persona: Flowly\n\n"
                "You are Flowly, a helpful AI assistant.\n\n"
                "## Personality\n\n"
                "- Helpful and friendly\n"
                "- Concise and to the point\n"
                "- Curious and eager to learn\n",
                encoding="utf-8",
            )
            console.print("  [dim]Created personas/default.md[/dim]")


