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

console = Console()

# Fields accepted by the server's FossilCreate model
_FOSSIL_CREATE_FIELDS = {
    "name", "description", "fossil_type", "source_prompt", "tags", "status",
    "reasoning_traces", "response_patterns", "decision_tree", "style_signature",
    "compression_ratio", "resurrection_count", "ethical_score",
}


def run(sources: list[str], output_json: bool = False) -> None:
    """Import fossil(s) from JSON files exported by `quark push`."""
    results = []
    for src in sources:
        path = Path(src)
        if not path.exists():
            console.print(f"[red]✗[/red] Fichier introuvable : {src}")
            continue
        try:
            raw = json.loads(path.read_text(encoding="utf-8"))
            # Filter to only FossilCreate-compatible fields to avoid 422
            payload = {k: v for k, v in raw.items() if k in _FOSSIL_CREATE_FIELDS}
            created = client.create_fossil(payload)
            fid = created.get("id", "?")
            results.append({"source": src, "id": fid})
            console.print(
                f"[green]✓[/green] {path.name}  → importé [dim]{fid[:8]}[/dim]  "
                f"[dim]{created.get('name', '')}[/dim]"
            )
        except client.QuarkError as e:
            console.print(f"[red]✗[/red] {path.name} : {e.detail}")
        except Exception as e:
            console.print(f"[red]✗[/red] {path.name} : {e}")

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