"""``bernstein init`` interactive wizard.

CLI-012: Ask questions and generate bernstein.yaml interactively.
"""

from __future__ import annotations

from pathlib import Path

import click

from bernstein.cli.helpers import SDD_DIRS, console

# ---------------------------------------------------------------------------
# Project type detection
# ---------------------------------------------------------------------------

_PROJECT_INDICATORS: dict[str, list[str]] = {
    "python": ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt"],
    "node": ["package.json"],
    "rust": ["Cargo.toml"],
    "go": ["go.mod"],
    "java": ["pom.xml", "build.gradle"],
    "ruby": ["Gemfile"],
}


def detect_project_type(root: Path) -> str:
    """Detect project type from marker files."""
    for ptype, markers in _PROJECT_INDICATORS.items():
        for marker in markers:
            if (root / marker).exists():
                return ptype
    return "generic"


# ---------------------------------------------------------------------------
# YAML generation
# ---------------------------------------------------------------------------


def generate_yaml(
    goal: str,
    project_type: str,
    max_agents: int,
    budget: float,
    adapter: str,
    approval: str,
) -> str:
    """Generate bernstein.yaml content from wizard answers.

    Args:
        goal: Project goal.
        project_type: Detected project type.
        max_agents: Maximum concurrent agents.
        budget: Cost cap in USD.
        adapter: Preferred adapter (auto/claude/codex/gemini).
        approval: Approval mode (auto/review/pr).

    Returns:
        YAML content string.
    """
    lines = [
        "# Bernstein configuration -- generated by 'bernstein init'",
        f"# Project type: {project_type}",
        "",
        f'goal: "{goal}"',
        "",
        "orchestrator:",
        f"  max_agents: {max_agents}",
        f"  budget_usd: {budget:.2f}",
        f"  approval: {approval}",
    ]

    if adapter != "auto":
        lines.extend(
            [
                "",
                "routing:",
                f"  default_adapter: {adapter}",
            ]
        )

    lines.extend(
        [
            "",
            "# Roles to use (uncomment to customize):",
            "# team:",
            "#   - backend",
            "#   - frontend",
            "#   - qa",
            "#   - security",
            "",
        ]
    )

    return "\n".join(lines) + "\n"


# ---------------------------------------------------------------------------
# CLI command
# ---------------------------------------------------------------------------


@click.command("init-wizard")
@click.option("--dir", "target_dir", default=".", show_default=True, help="Directory to initialise.")
@click.option("--non-interactive", is_flag=True, default=False, help="Use defaults without prompting.")
def init_wizard_cmd(target_dir: str, non_interactive: bool) -> None:
    """Interactive wizard to set up a Bernstein project.

    \b
    Asks questions about your project and generates:
      - .sdd/ directory structure
      - bernstein.yaml configuration file

    \b
    Examples:
      bernstein init-wizard                    # interactive setup
      bernstein init-wizard --non-interactive  # use defaults
    """
    root = Path(target_dir).resolve()

    console.print("\n[bold cyan]Bernstein Project Setup Wizard[/bold cyan]\n")

    # Detect project type
    project_type = detect_project_type(root)
    if project_type != "generic":
        console.print(f"  [green]Detected:[/green] {project_type} project\n")

    if non_interactive:
        goal = f"Improve this {project_type} project"
        max_agents = 3
        budget = 5.0
        adapter = "auto"
        approval = "auto"
    else:
        # Ask questions
        goal = click.prompt(
            "  Project goal",
            default=f"Improve this {project_type} project",
        )

        max_agents = click.prompt(
            "  Max concurrent agents",
            type=int,
            default=3,
        )

        budget = click.prompt(
            "  Budget cap (USD, 0 = unlimited)",
            type=float,
            default=5.0,
        )

        adapter = click.prompt(
            "  Preferred adapter",
            type=click.Choice(["auto", "claude", "codex", "gemini"]),
            default="auto",
        )

        approval = click.prompt(
            "  Approval mode",
            type=click.Choice(["auto", "review", "pr"]),
            default="auto",
        )

    # Create directories
    console.print("\n[bold]Creating workspace...[/bold]")
    for d in SDD_DIRS:
        p = root / d
        p.mkdir(parents=True, exist_ok=True)

    # Write config
    yaml_content = generate_yaml(goal, project_type, max_agents, budget, adapter, approval)
    yaml_path = root / "bernstein.yaml"
    if yaml_path.exists() and not non_interactive:
        overwrite = click.confirm(f"  {yaml_path.name} already exists. Overwrite?", default=False)
        if not overwrite:
            console.print("[dim]  Skipped bernstein.yaml[/dim]")
        else:
            yaml_path.write_text(yaml_content)
            console.print(f"  [green]Updated[/green] {yaml_path.name}")
    else:
        yaml_path.write_text(yaml_content)
        console.print(f"  [green]Created[/green] {yaml_path.name}")

    # Write .sdd/config.yaml if not present
    sdd_config = root / ".sdd" / "config.yaml"
    if not sdd_config.exists():
        sdd_config.write_text(
            "# Bernstein workspace config\n"
            "server_port: 8052\n"
            f"max_workers: {max_agents}\n"
            "default_model: sonnet\n"
            "default_effort: high\n"
        )
        console.print("  [green]Created[/green] .sdd/config.yaml")

    # Write .gitignore for runtime
    gi_path = root / ".sdd" / "runtime" / ".gitignore"
    if not gi_path.exists():
        gi_path.parent.mkdir(parents=True, exist_ok=True)
        gi_path.write_text("*.pid\n*.log\n")

    console.print("\n[bold green]Done![/bold green] Run [cyan]bernstein doctor[/cyan] to verify setup.")
    console.print(f'Then: [cyan]bernstein run[/cyan] or [cyan]bernstein -g "{goal}"[/cyan]\n')
