"""abreka exp update — update experiment metadata."""

from __future__ import annotations

import click

from abreka.config import find_abreka_dir
from abreka.metrics import parse_metric_spec
from abreka.models import ExperimentStatus
from abreka.persistence import (
    load_experiment,
    normalize_exp_id,
    save_experiment,
    update_index_entry,
)


@click.command("update")
@click.argument("exp_id")
@click.option("--hypothesis", default=None, help="Set hypothesis text.")
@click.option("--method", default=None, help="Set method text.")
@click.option("--status", "new_status", default=None,
              type=click.Choice([s.value for s in ExperimentStatus]),
              help="Set status manually.")
@click.option("--parent", "parents", multiple=True, help="Set parent IDs (replaces existing).")
@click.option("--metric", "metrics", multiple=True, help="Set metric: [split:]key=value")
@click.option("--tag", "tags", multiple=True, help="Set tags (replaces existing).")
def update_cmd(exp_id: str, hypothesis: str | None, method: str | None,
               new_status: str | None, parents: tuple[str, ...],
               metrics: tuple[str, ...], tags: tuple[str, ...]):
    """Update experiment metadata."""
    abreka_dir = find_abreka_dir()
    exp_id = normalize_exp_id(exp_id)
    exp = load_experiment(abreka_dir, exp_id)

    if hypothesis is not None:
        exp.hypothesis = hypothesis
    if method is not None:
        exp.method = method
    if new_status is not None:
        exp.status = ExperimentStatus(new_status)
    if parents:
        exp.parents = list(parents)
    if tags:
        exp.tags = list(tags)
    for spec in metrics:
        split, key, value = parse_metric_spec(spec)
        if split not in exp.metrics:
            exp.metrics[split] = {}
        exp.metrics[split][key] = value

    save_experiment(exp, abreka_dir)
    update_index_entry(abreka_dir, exp)
    click.echo(f"Updated experiment {exp_id}")
