"""abreka wiki list — list wiki pages."""

from __future__ import annotations

import click
from rich.console import Console
from rich.table import Table

from abreka.config import find_abreka_dir
from abreka.wiki import load_wiki_index


@click.command("list")
@click.option("--tag", default=None, help="Filter to pages with this tag.")
@click.option("--json", "as_json", is_flag=True, help="Emit JSON instead of a table.")
def list_cmd(tag: str | None, as_json: bool):
    """List wiki pages with title, tags, and summary."""
    abreka_dir = find_abreka_dir()
    index = load_wiki_index(abreka_dir)

    entries = sorted(index.values(), key=lambda e: e.get("slug", ""))
    if tag:
        entries = [e for e in entries if tag in e.get("tags", [])]

    if as_json:
        import json

        click.echo(json.dumps(entries, indent=2))
        return

    if not entries:
        click.echo("No wiki pages.")
        return

    console = Console()
    table = Table(show_header=True, header_style="bold")
    table.add_column("Slug", style="bold")
    table.add_column("Title")
    table.add_column("Tags")
    table.add_column("Summary")
    table.add_column("Updated")

    for e in entries:
        table.add_row(
            e.get("slug", ""),
            e.get("title", ""),
            ", ".join(e.get("tags", [])),
            e.get("summary", ""),
            e.get("updated_at", "")[:10],
        )
    console.print(table)
