"""abreka wiki edit — replace fields on an existing wiki page."""

from __future__ import annotations

from datetime import datetime, timezone

import click

from abreka.cli.wiki._io import resolve_content
from abreka.config import find_abreka_dir
from abreka.wiki import (
    WikiPageNotFoundError,
    load_wiki_page,
    save_wiki_page,
)


@click.command("edit")
@click.argument("slug")
@click.option("--title", default=None, help="Replace the title.")
@click.option("--summary", default=None, help="Replace the summary.")
@click.option(
    "--tag",
    "tags",
    multiple=True,
    help="Replace the tag list. Repeat to set multiple.",
)
@click.option("--content", "-c", default=None, help="Replace the body.")
@click.option(
    "--content-file",
    default=None,
    help="Read replacement body from a file. Use '-' for stdin.",
)
@click.option("--exp", "exp_id", default="", help="Experiment id recording this edit.")
def edit_cmd(
    slug: str,
    title: str | None,
    summary: str | None,
    tags: tuple[str, ...],
    content: str | None,
    content_file: str | None,
    exp_id: str,
):
    """Update an existing wiki page's title, summary, tags, or body."""
    abreka_dir = find_abreka_dir()
    body = resolve_content(content, content_file)

    if title is None and summary is None and not tags and body is None:
        raise click.ClickException(
            "Provide --title, --summary, --tag, or --content/--content-file."
        )

    try:
        page = load_wiki_page(abreka_dir, slug)
    except WikiPageNotFoundError as exc:
        raise click.ClickException(str(exc))

    if title is not None:
        page.title = title
    if summary is not None:
        page.summary = summary
    if tags:
        page.tags = list(tags)
    if body is not None:
        page.body = body
    if exp_id:
        page.updated_by_exp = exp_id
    page.updated_at = datetime.now(timezone.utc)

    save_wiki_page(page, abreka_dir)
    click.echo(f"Updated {page.slug}")
