"""abreka init — initialize ABREKA in a uv project."""

from __future__ import annotations

import json
import shutil
from importlib.resources import files as pkg_files
from pathlib import Path

import click

from abreka.config import discover_project, save_config
from abreka.models import Config, ProjectConfig
from abreka.prompts import get_default_template


def init_project(project_path: Path) -> tuple[str, str]:
    """Initialize ABREKA in a uv project directory.

    Returns (project_name, lib_name).
    Raises exceptions (not click.ClickException) on failure.
    """
    abreka_dir = project_path / "abreka"

    if (abreka_dir / "config.toml").is_file():
        raise FileExistsError(f"ABREKA already initialized at {abreka_dir}")

    project_name, lib_name = discover_project(project_path)

    # Create directory structure
    abreka_dir.mkdir(exist_ok=True)
    (abreka_dir / "experiments").mkdir(exist_ok=True)
    (abreka_dir / "prompts").mkdir(exist_ok=True)
    (abreka_dir / "artifacts" / "shared").mkdir(parents=True, exist_ok=True)

    # Write config.toml
    config = Config(project=ProjectConfig(name=project_name, lib=lib_name))
    save_config(config, abreka_dir)

    # Write goal.md
    default_goal = (pkg_files("abreka.defaults") / "goal.md").read_text(encoding="utf-8")
    (abreka_dir / "goal.md").write_text(default_goal)

    # Write default prompt templates
    for name in ("propose_exploit", "propose_explore", "implement", "test", "repair_run", "evaluate"):
        template = get_default_template(name)
        (abreka_dir / "prompts" / f"{name}.md").write_text(template)

    # Write .rgignore so agent ripgrep searches skip bulky run artifacts while
    # keeping curated shared artifacts searchable.
    (abreka_dir / ".rgignore").write_text(
        "experiments/*/artifacts/\n"
        "artifacts/*\n"
        "!artifacts/shared/\n"
        "!artifacts/shared/**\n"
    )

    # Write empty indexes
    (abreka_dir / "index.json").write_text("{}\n")

    # Create backlog directory and index
    (abreka_dir / "backlog").mkdir(exist_ok=True)
    (abreka_dir / "backlog_index.json").write_text("{}\n")

    # Create wiki directory and index
    (abreka_dir / "wiki" / "pages").mkdir(parents=True, exist_ok=True)
    (abreka_dir / "wiki_index.json").write_text("{}\n")

    return project_name, lib_name


@click.command("init")
@click.argument("path", default=".", type=click.Path(exists=True, file_okay=False, resolve_path=True))
def init_cmd(path: str):
    """Initialize ABREKA in an existing uv project directory."""
    project_path = Path(path)

    try:
        project_name, lib_name = init_project(project_path)
    except FileExistsError as e:
        raise click.ClickException(str(e))
    except Exception as e:
        raise click.ClickException(str(e))

    click.echo(f"Discovered project: {project_name} (lib: {lib_name})")
    click.echo("Created abreka/config.toml")
    click.echo("Created abreka/goal.md")
    click.echo("Created abreka/prompts/ with default templates")
    click.echo("Created abreka/artifacts/shared/")
    click.echo("Created abreka/index.json")
    click.echo("Created abreka/backlog/")
    click.echo("Created abreka/wiki/pages/")

    click.echo(f"\nABREKA initialized in {project_path / 'abreka'}")
    click.echo("Next: edit abreka/goal.md to describe your research objective.")
