"""abreka wiki append — add a dated note to a wiki page's History section."""

from __future__ import annotations

import click

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


@click.command("append")
@click.argument("slug")
@click.option("--content", "-c", default=None, help="Note text to append.")
@click.option(
    "--content-file",
    default=None,
    help="Read note text from a file. Use '-' for stdin.",
)
@click.option("--exp", "exp_id", default="", help="Experiment id recording this note.")
def append_cmd(slug: str, content: str | None, content_file: str | None, exp_id: str):
    """Append a dated note under the page's `## History` section."""
    abreka_dir = find_abreka_dir()
    note = resolve_content(content, content_file)
    if not note or not note.strip():
        raise click.ClickException("Provide --content or --content-file.")

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

    append_history(page, note, exp_id=exp_id)
    save_wiki_page(page, abreka_dir)
    click.echo(f"Appended to {page.slug}")
