"""abreka wiki add — create a new wiki page."""

from __future__ import annotations

import click

from abreka.cli.wiki._io import resolve_content
from abreka.config import find_abreka_dir
from abreka.models import WikiPage
from abreka.wiki import (
    InvalidSlugError,
    normalize_slug,
    save_wiki_page,
    wiki_page_path,
)


@click.command("add")
@click.option("--title", "-t", required=True, help="Page title.")
@click.option(
    "--slug",
    default=None,
    help="Slug (kebab-case). Derived from --title when omitted.",
)
@click.option("--summary", default="", help="One-line summary shown in the wiki index.")
@click.option(
    "--tag",
    "tags",
    multiple=True,
    help="Tag for categorization. Repeat to add several.",
)
@click.option("--content", "-c", default=None, help="Page body (markdown).")
@click.option(
    "--content-file",
    default=None,
    help="Read body from a file. Use '-' for stdin.",
)
@click.option(
    "--exp",
    "exp_id",
    default="",
    help="Experiment id authoring this page (recorded as created_by_exp).",
)
def add_cmd(
    title: str,
    slug: str | None,
    summary: str,
    tags: tuple[str, ...],
    content: str | None,
    content_file: str | None,
    exp_id: str,
):
    """Create a new wiki page."""
    abreka_dir = find_abreka_dir()
    body = resolve_content(content, content_file) or ""

    try:
        normalized = normalize_slug(slug or title)
    except InvalidSlugError as exc:
        raise click.ClickException(str(exc))

    if wiki_page_path(abreka_dir, normalized).is_file():
        raise click.ClickException(
            f"Wiki page {normalized!r} already exists. Use 'wiki edit' or pick another slug."
        )

    page = WikiPage(
        slug=normalized,
        title=title,
        summary=summary,
        tags=list(tags),
        body=body,
        created_by_exp=exp_id,
        updated_by_exp=exp_id,
    )
    save_wiki_page(page, abreka_dir)
    click.echo(page.slug)
