"""appxen sources — list and delete knowledge base sources."""

from __future__ import annotations

import typer

from appxen_cli.display import console, error, sources_table, success

app = typer.Typer(help="Manage RAG knowledge base sources.")


@app.callback(invoke_without_command=True)
def list_sources(
    ctx: typer.Context,
    status_filter: str = typer.Option(None, "--status", "-s", help="Filter by status"),
    search: str = typer.Option(None, "--search", "-q", help="Search by filename"),
    limit: int = typer.Option(20, "--limit", "-n", help="Results per page"),
    offset: int = typer.Option(0, "--offset", help="Pagination offset"),
    json_output: bool = typer.Option(False, "--json", help="Output raw JSON"),
) -> None:
    """List knowledge base sources (default command)."""
    if ctx.invoked_subcommand is not None:
        return

    from appxen_cli.main import get_client
    from appxen_cli.display import print_json

    try:
        client = get_client()
    except typer.Exit:
        raise

    try:
        data = client.list_sources(
            limit=limit,
            offset=offset,
            status_filter=status_filter,
            search=search,
        )
    except Exception as e:
        error(f"Failed to list sources: {e}")
        raise typer.Exit(1)

    if json_output:
        print_json(data)
        return

    srcs = data.get("sources", [])
    total = data.get("total", len(srcs))
    sources_table(srcs, total, offset)


@app.command()
def delete(
    source_id: str = typer.Argument(..., help="Source ID to delete"),
    yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"),
) -> None:
    """Delete a source and its chunks."""
    from appxen_cli.main import get_client

    if not yes:
        confirm = typer.confirm(f"Delete source {source_id}?")
        if not confirm:
            raise typer.Abort()

    try:
        client = get_client()
    except typer.Exit:
        raise

    try:
        client.delete_source(source_id)
        success(f"Deleted source {source_id}")
    except Exception as e:
        error(f"Failed to delete source: {e}")
        raise typer.Exit(1)
