from quark import client
from rich.console import Console
from rich.table import Table
import json

console = Console()

_BAR = 10


def _parse_tags(raw) -> list[str]:
    if isinstance(raw, list):
        return raw
    if isinstance(raw, str):
        try:
            return json.loads(raw)
        except Exception:
            return [raw] if raw else []
    return []


def _sigma(score) -> str:
    if score is None:
        return "[dim]—[/dim]"
    color = "green" if score >= 0.80 else "yellow" if score >= 0.60 else "red"
    filled = round(score * _BAR)
    bar = "█" * filled + "░" * (_BAR - filled)
    return f"[{color}]{bar} {score:.3f}[/{color}]"


def run(agent: str = "", tag: str = "", limit: int = 30,
        oneline: bool = False, output_json: bool = False) -> None:
    """Show the ordered history of cognitive fossils."""
    try:
        fossils = client.list_fossils(limit=limit)
    except client.QuarkError as e:
        console.print(f"[red]✗ {e.status}[/red] : {e.detail}")
        raise SystemExit(1)

    if agent:
        fossils = [f for f in fossils if agent.lower() in (f.get("name") or "").lower()]
    if tag:
        fossils = [f for f in fossils if tag in _parse_tags(f.get("tags"))]

    # API already returns DESC, but ensure it
    fossils.sort(key=lambda f: f.get("created_date") or "", reverse=True)
    fossils = fossils[:limit]

    if output_json:
        print(json.dumps(fossils, indent=2))
        return

    if not fossils:
        console.print("[dim]Aucun fossile.[/dim]")
        return

    if oneline:
        for f in fossils:
            fid   = (f.get("id") or "")[:8]
            name  = f.get("name", "?")
            score = f.get("stability_score")
            date  = (f.get("created_date") or "")[:10]
            tags  = " ".join(f"[{t}]" for t in _parse_tags(f.get("tags")))
            color = "green" if (score or 0) >= 0.80 else "yellow" if (score or 0) >= 0.60 else "red"
            score_s = f"[{color}]{score:.3f}[/{color}]" if score is not None else "[dim]—[/dim]"
            console.print(f"[dim]{fid}[/dim]  {score_s}  [bold]{name}[/bold]  [dim]{date}  {tags}[/dim]")
        return

    t = Table(show_header=True, header_style="bold dim")
    t.add_column("ID",    style="dim", width=9)
    t.add_column("Agent", min_width=20)
    t.add_column("σ stability",   min_width=18)
    t.add_column("Type",  width=20, style="dim")
    t.add_column("Tags",  style="dim")
    t.add_column("Date",  width=10, style="dim")

    for f in fossils:
        tags = _parse_tags(f.get("tags"))
        t.add_row(
            (f.get("id") or "")[:8],
            f.get("name", ""),
            _sigma(f.get("stability_score")),
            f.get("fossil_type", ""),
            ", ".join(tags[:3]),
            (f.get("created_date") or "")[:10],
        )
    console.print()
    console.print(t)
    console.print(f"  [dim]{len(fossils)} fossile(s)[/dim]")
