"""abreka exp delete — remove an experiment."""

from __future__ import annotations

import shutil

import click

from abreka.config import find_abreka_dir, load_index, save_index
from abreka.persistence import experiment_dir, normalize_exp_id


@click.command("delete")
@click.argument("exp_id")
@click.option("--yes", "-y", is_flag=True, help="Skip confirmation.")
def delete_cmd(exp_id: str, yes: bool):
    """Delete an experiment directory and remove it from the index."""
    abreka_dir = find_abreka_dir()
    exp_id = normalize_exp_id(exp_id)

    exp_path = experiment_dir(abreka_dir, exp_id)
    index = load_index(abreka_dir)

    if exp_id not in index and not exp_path.exists():
        raise click.ClickException(f"Experiment {exp_id} not found.")

    if not yes:
        click.confirm(f"Delete experiment {exp_id}?", abort=True)

    if exp_path.exists():
        shutil.rmtree(exp_path)

    if exp_id in index:
        del index[exp_id]
        save_index(index, abreka_dir)

    click.echo(f"Deleted experiment {exp_id}")
