from pathlib import Path
from quark import client
from rich.console import Console
import json

console = Console()


def run(fossil_ids: list[str], agent: str = "", output_dir: str = "", output_json: bool = False) -> None:
    """Export fossils to .quark/fossils/ for team sharing via git."""
    out_path = Path(output_dir) if output_dir else Path(".quark/fossils")
    out_path.mkdir(parents=True, exist_ok=True)

    # Resolve IDs — explicit list or agent filter
    if not fossil_ids:
        if not agent:
            console.print("[red]✗[/red] Fournir des IDs ou [bold]--agent[/bold].")
            raise SystemExit(1)
        try:
            all_f = client.list_fossils(limit=500)
            fossil_ids = [f["id"] for f in all_f
                         if agent.lower() in (f.get("name") or "").lower()]
        except client.QuarkError as e:
            console.print(f"[red]✗ {e.status}[/red] : {e.detail}")
            raise SystemExit(1)

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

    results = []
    for fid in fossil_ids:
        try:
            fossil = client.get_fossil(fid)
            slug   = (fossil.get("name") or "fossil").replace(" ", "_")
            fname  = out_path / f"{fid[:8]}_{slug}.json"
            fname.write_text(json.dumps(fossil, indent=2, ensure_ascii=False), encoding="utf-8")
            results.append({"id": fid, "file": str(fname)})
            score  = fossil.get("stability_score")
            score_s = f"σ={score:.3f}" if score is not None else ""
            console.print(f"[green]✓[/green] {fid[:8]}  {fossil.get('name','?'):<28} {score_s}  → {fname.name}")
        except client.QuarkError as e:
            console.print(f"[red]✗[/red] {fid[:8]} : {e.detail}")

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

    console.print()
    console.print(f"  [dim]{len(results)} fossile(s) exporté(s) dans {out_path}/[/dim]")
    console.print("  [dim]git add .quark/fossils/ && git commit -m 'chore: push fossils'[/dim]")
