"""CLI `binex init` command — interactive project initialisation."""

from __future__ import annotations

from pathlib import Path

import click

from binex.cli.providers import PROVIDERS, ProviderConfig

# Ordered list for the numbered menu.
_PROVIDER_LIST: list[ProviderConfig] = list(PROVIDERS.values())


# ---- templates ---------------------------------------------------------------

def _workflow_yaml(project_name: str, agent_prefix: str, model: str) -> str:
    agent_ref = f"{agent_prefix}{model}"
    return f'''name: "{project_name}"
description: "Generated by binex init"
nodes:
  planner:
    agent: "{agent_ref}"
    system_prompt: "Plan the research on the given topic"
    inputs:
      topic: "${{user.topic}}"
    outputs: [plan]
    depends_on: []
  researcher:
    agent: "{agent_ref}"
    system_prompt: "Research based on the plan"
    inputs:
      plan: "${{planner.plan}}"
    outputs: [findings]
    depends_on: [planner]
  writer:
    agent: "{agent_ref}"
    system_prompt: "Write a summary based on research findings"
    inputs:
      findings: "${{researcher.findings}}"
    outputs: [summary]
    depends_on: [researcher]
'''


def _env_example(env_var: str | None) -> str:
    lines = ["# Environment variables for Binex project", ""]
    if env_var:
        lines.append(f"{env_var}=your-key-here")
        lines.append("")
    return "\n".join(lines)


_GITIGNORE = """\
# Python
__pycache__/
*.py[cod]
*.egg-info/
dist/
build/
.eggs/
*.egg
.venv/
venv/

# Binex
.binex/

# IDE
.idea/
.vscode/
*.swp

# Environment
.env
"""


def _docker_compose_yml() -> str:
    return """\
services:
  ollama:
    image: ollama/ollama:latest
    ports:
      - "11434:11434"
    volumes:
      - ollama_data:/root/.ollama

volumes:
  ollama_data:
"""


def _test_workflow_py() -> str:
    return '''\
"""Skeleton test for the project workflow."""

from pathlib import Path


def test_workflow_file_exists() -> None:
    """Verify that workflow.yaml exists in the project root."""
    assert Path("workflow.yaml").exists() or True  # placeholder
'''


# ---- command -----------------------------------------------------------------

@click.command("init")
@click.option("--name", "project_name", default=None, help="Project name (skips prompt)")
def init_cmd(project_name: str | None) -> None:
    """Initialise a new Binex project interactively."""

    cwd = Path.cwd()

    # T017 — non-empty directory check
    if any(cwd.iterdir()):
        if not click.confirm(
            "Current directory is not empty. Continue anyway?", default=False
        ):
            click.echo("Aborted.")
            return

    # 1. Project name
    if project_name is None:
        project_name = click.prompt("Project name", default=cwd.name)

    # 2. Mode
    click.echo("\nSelect mode:")
    click.echo("  1) workflow — single workflow.yaml")
    click.echo("  2) agent    — workflow + agent scaffold")
    click.echo("  3) full     — workflow + agent + tests + docker")
    mode = click.prompt("Mode", type=int, default=1)
    if mode not in (1, 2, 3):
        click.echo("Invalid mode. Defaulting to workflow.")
        mode = 1

    # 3. Provider
    click.echo("\nSelect LLM provider:")
    for idx, prov in enumerate(_PROVIDER_LIST, 1):
        click.echo(f"  {idx}) {prov.name}")
    click.echo(f"  {len(_PROVIDER_LIST) + 1}) skip")
    provider_choice = click.prompt("Provider", type=int, default=1)

    provider: ProviderConfig | None = None
    if 1 <= provider_choice <= len(_PROVIDER_LIST):
        provider = _PROVIDER_LIST[provider_choice - 1]

    # 4. Model
    if provider is not None:
        model = click.prompt("Model", default=provider.default_model)
        agent_prefix = provider.agent_prefix
        env_var = provider.env_var
    else:
        model = "ollama/llama3.2"
        agent_prefix = "llm://ollama/"
        env_var = None

    # ---- generate files ----

    # Always: workflow.yaml, .env.example, .gitignore
    (cwd / "workflow.yaml").write_text(_workflow_yaml(project_name, agent_prefix, model))
    (cwd / ".env.example").write_text(_env_example(env_var))
    (cwd / ".gitignore").write_text(_GITIGNORE)

    created = ["workflow.yaml", ".env.example", ".gitignore"]

    # Agent mode (2 or 3): create agents/<project_name>/
    if mode >= 2:
        agents_dir = cwd / "agents" / project_name
        agents_dir.mkdir(parents=True, exist_ok=True)
        (agents_dir / "__init__.py").write_text("")
        (agents_dir / "agent.py").write_text(
            f'"""Agent handler for {project_name}."""\n'
        )
        created.append(f"agents/{project_name}/")

    # Full mode (3): workflows/, tests/, docker-compose.yml
    if mode == 3:
        (cwd / "workflows").mkdir(exist_ok=True)
        created.append("workflows/")

        tests_dir = cwd / "tests"
        tests_dir.mkdir(exist_ok=True)
        (tests_dir / "__init__.py").write_text("")
        (tests_dir / "test_workflow.py").write_text(_test_workflow_py())
        created.append("tests/")

        (cwd / "docker-compose.yml").write_text(_docker_compose_yml())
        created.append("docker-compose.yml")

    # ---- summary ----
    click.echo(f"\nProject '{project_name}' initialised!")
    click.echo("Created:")
    for f in created:
        click.echo(f"  {f}")
    click.echo("\nRun your workflow:\n  binex run workflow.yaml --var topic=\"your topic\"")
