"""abreka backlog edit — update backlog item fields."""

from __future__ import annotations

from datetime import datetime, timezone

import click

from abreka.config import find_abreka_dir
from abreka.persistence import (
    load_backlog_item,
    normalize_backlog_id,
    save_backlog_item,
    update_backlog_index_entry,
)


@click.command("edit")
@click.argument("item_id")
@click.option("--title", default=None, help="Set title.")
@click.option("--description", default=None, help="Set description.")
@click.option("--tag", "tags", multiple=True, help="Set tags (replaces existing).")
@click.option("--priority", type=int, default=None, help="Set priority.")
@click.option("--source-exp", default=None, help="Set source experiment ID.")
def edit_cmd(item_id: str, title: str | None, description: str | None,
             tags: tuple[str, ...], priority: int | None, source_exp: str | None):
    """Update fields on an existing backlog item."""
    abreka_dir = find_abreka_dir()
    item_id = normalize_backlog_id(item_id)
    item = load_backlog_item(abreka_dir, item_id)

    if title is not None:
        item.title = title
    if description is not None:
        item.description = description
    if tags:
        item.tags = list(tags)
    if priority is not None:
        item.priority = priority
    if source_exp is not None:
        item.source_exp = source_exp

    item.updated_at = datetime.now(timezone.utc)

    save_backlog_item(item, abreka_dir)
    update_backlog_index_entry(abreka_dir, item)
    click.echo(f"Updated backlog item {item_id}")
