"""abreka backlog list — list backlog items with filtering and sorting."""

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.persistence import load_backlog_index


@click.command("list")
@click.option("--status", "-s", default=None, help="Filter by status (open/resolved/dismissed).")
@click.option("--tag", default=None, help="Filter by tag.")
@click.option("--sort", "sort_by", default="priority",
              type=click.Choice(["priority", "time", "id"]),
              help="Sort order.")
def list_cmd(status: str | None, tag: str | None, sort_by: str):
    """List backlog items with optional filtering and sorting."""
    abreka_dir = find_abreka_dir()
    index = load_backlog_index(abreka_dir)

    if not index:
        click.echo("No backlog items yet.")
        return

    entries = list(index.values())

    if status:
        entries = [e for e in entries if e["status"] == status]
    if tag:
        entries = [e for e in entries if tag in e.get("tags", [])]

    if sort_by == "priority":
        entries.sort(key=lambda e: e.get("priority", 0), reverse=True)
    elif sort_by == "time":
        entries.sort(key=lambda e: e.get("created_at", ""), reverse=True)
    else:
        entries.sort(key=lambda e: e["id"])

    console = Console()
    table = Table(show_header=True, header_style="bold")
    table.add_column("ID", style="bold")
    table.add_column("Pri", justify="right")
    table.add_column("Status")
    table.add_column("Title", max_width=50, no_wrap=True)
    table.add_column("Tags")
    table.add_column("Source")

    status_styles = {
        "open": "cyan",
        "resolved": "green",
        "dismissed": "dim",
    }

    for e in entries:
        style = status_styles.get(e["status"], "")
        table.add_row(
            e["id"],
            str(e.get("priority", 0)),
            f"[{style}]{e['status']}[/{style}]",
            e.get("title", "")[:50],
            ", ".join(e.get("tags", [])),
            e.get("source_exp", ""),
        )

    console.print(table)
