"""quark list — list fossils in the repository."""
from __future__ import annotations

import json
import typer
from rich.console import Console
from rich.table import Table
from rich import box

from quark import client

console = Console()


def run(
    limit: int  = typer.Option(20, "--limit", "-n"),
    output_json: bool = typer.Option(False, "--json"),
):
    """List fossils stored in your Quark-AI repository."""
    with console.status("[cyan]Fetching fossils…[/cyan]"):
        try:
            fossils = client.list_fossils(limit=limit)
        except client.QuarkError as e:
            console.print(f"[bold red]✗[/bold red] {e.detail}")
            raise typer.Exit(1)

    if output_json:
        console.print_json(json.dumps(fossils))
        return

    if not fossils:
        console.print("[dim]No fossils yet. Run `quark snapshot` to capture one.[/dim]")
        return

    t = Table(box=box.SIMPLE, header_style="bold dim")
    t.add_column("ID",          width=10, style="dim")
    t.add_column("Name",        width=28)
    t.add_column("Type",        width=20, style="dim")
    t.add_column("σ",           width=6,  justify="right")
    t.add_column("Tags",        width=20, style="dim")
    t.add_column("Created",     width=12, style="dim")

    for f in fossils:
        score = f.get("stability_score")
        score_s = f"{score:.2f}" if score is not None else "—"
        score_color = (
            "green" if (score or 0) >= 0.80
            else "yellow" if (score or 0) >= 0.60
            else "red"
        )
        tags = f.get("tags") or []
        if isinstance(tags, str):
            try:
                tags = json.loads(tags)
            except Exception:
                tags = []
        created = (f.get("created_date") or "")[:10]

        t.add_row(
            f["id"][:8] + "…",
            f.get("name", "—"),
            f.get("fossil_type", "—"),
            f"[{score_color}]{score_s}[/{score_color}]",
            ", ".join(tags[:3]),
            created,
        )

    console.print()
    console.print(t)
    console.print(f"  [dim]{len(fossils)} fossil(s)[/dim]")
    console.print()
