"""abreka bootstrap — create and set up a new research project."""

from __future__ import annotations

import os
import shutil
import subprocess
from importlib.resources import files as pkg_files
from pathlib import Path

import click

from abreka.cli.init_cmd import init_project
from abreka.prompts import render_template


@click.command("bootstrap")
@click.argument("project_name", required=False)
@click.option("--no-agent", is_flag=True, help="Skip the interactive pi session.")
def bootstrap_cmd(project_name: str | None, no_agent: bool):
    """Create a new research project and launch an interactive setup session.

    Creates a uv project, initializes abreka, then launches pi in interactive
    mode to help you write your research goal, choose metrics, install
    dependencies, and create initial shared library code.
    """
    # Resolve project name
    if not project_name:
        project_name = click.prompt("Project name")

    project_path = Path.cwd() / project_name

    # Validate environment
    if project_path.exists():
        raise click.ClickException(f"Directory '{project_name}' already exists.")

    if not shutil.which("uv"):
        raise click.ClickException(
            "uv not found. Install it: https://docs.astral.sh/uv/"
        )

    if not no_agent and not shutil.which("pi"):
        raise click.ClickException(
            "pi not found. Install it: https://github.com/badlogic/pi-mono\n\n"
            "Or use --no-agent to skip the interactive setup."
        )

    # Create uv project
    click.echo(f"Creating uv project: {project_name}")
    subprocess.run(["uv", "init", "--app", "--package", project_name], check=True)

    # Initialize abreka
    click.echo("Initializing abreka...")
    try:
        proj_name, lib_name = init_project(project_path)
    except Exception as e:
        raise click.ClickException(f"Failed to initialize abreka: {e}")

    click.echo(f"Project '{proj_name}' (lib: {lib_name}) is ready.\n")

    if no_agent:
        click.echo("Next steps:")
        click.echo(f"  cd {project_name}")
        click.echo(f"  $EDITOR abreka/goal.md          # Write your research goal")
        click.echo(f"  $EDITOR abreka/config.toml       # Tune primary metric, timeouts")
        click.echo(f"  uv add <dependencies>            # Add libraries")
        click.echo(f"  uv run abreka run --step         # Run first experiment loop")
        return

    # Build system prompt for pi
    template = (
        pkg_files("abreka.defaults") / "bootstrap_prompt.md"
    ).read_text(encoding="utf-8")
    system_prompt = render_template(template, {
        "project_name": project_name,
        "lib_name": lib_name,
    })

    # Launch pi interactively
    click.echo("Launching interactive setup with pi...\n")
    os.chdir(project_path)
    os.execvp("pi", [
        "pi",
        "--append-system-prompt", system_prompt,
        "--no-session",
        f"I just created a new abreka research project called '{project_name}'. "
        "Let's set it up together. What are you trying to research?",
    ])
