"""quark restore — export the behavioral spec of a past fossil for reuse."""
from __future__ import annotations

import json
import typer
from pathlib import Path
from rich.console import Console
from rich.panel import Panel
from rich.syntax import Syntax
from rich import box

from quark import client

console = Console()


def run(
    fossil_id: str = typer.Argument(..., metavar="FOSSIL_ID"),
    to: str = typer.Option(
        "",
        "--to",
        help="Write behavior card to a file (e.g. --to staging.md)",
    ),
    format: str = typer.Option(
        "markdown",
        "--format",
        help="Output format: markdown | json | prompt",
    ),
    output_json: bool = typer.Option(False, "--json"),
):
    """
    Export the behavioral specification of a past fossil.

    Use this to reproduce a specific agent behavior in a new environment —
    paste the output into your system prompt, CI config, or LLM wrapper.

    Examples:

      quark restore abc123

      quark restore abc123 --to staging_prompt.md

      quark restore abc123 --format prompt | pbcopy
    """
    with console.status("[cyan]Loading fossil…[/cyan]"):
        try:
            fossil = client.get_fossil(fossil_id)
        except client.QuarkError as e:
            console.print(f"[bold red]✗[/bold red] {e.detail}")
            raise typer.Exit(1)

    name    = fossil.get("name", "—")
    ftype   = fossil.get("fossil_type", "—")
    score   = fossil.get("stability_score")
    score_s = f"{score:.3f}" if score is not None else "—"
    src     = fossil.get("source_prompt", "")
    sig     = fossil.get("cognitive_signature", "")
    tags    = fossil.get("tags") or []
    if isinstance(tags, str):
        try:
            tags = json.loads(tags)
        except Exception:
            tags = []
    created = (fossil.get("created_date") or "")[:10]

    inv = fossil.get("behavioral_invariants") or []
    if isinstance(inv, str):
        try:
            inv = json.loads(inv)
        except Exception:
            inv = []
    inv_texts = [
        i.get("description", str(i)) if isinstance(i, dict) else str(i)
        for i in inv
    ]

    zones = fossil.get("sensitive_zones") or []
    if isinstance(zones, str):
        try:
            zones = json.loads(zones)
        except Exception:
            zones = []
    zone_texts = [
        z.get("description", str(z)) if isinstance(z, dict) else str(z)
        for z in zones
    ]

    # ── Build behavior card ───────────────────────────────────────────────────
    if output_json or format == "json":
        card = {
            "fossil_id":   fossil["id"],
            "name":        name,
            "fossil_type": ftype,
            "stability":   score,
            "created":     created,
            "source_prompt":          src,
            "cognitive_signature":    sig,
            "behavioral_invariants":  inv_texts,
            "sensitive_zones":        zone_texts,
        }
        out = json.dumps(card, ensure_ascii=False, indent=2)
        if to:
            Path(to).write_text(out)
            console.print(f"[green]✓[/green] Written to [bold]{to}[/bold]")
        else:
            console.print_json(out)
        return

    if format == "prompt":
        # Minimal system-prompt-ready block
        lines = [f"# Agent: {name}  (fossil {fossil['id'][:8]}, σ={score_s})"]
        if src:
            lines += ["", "## Role", src]
        if inv_texts:
            lines += ["", "## Behavioral constraints"]
            lines += [f"- {i}" for i in inv_texts]
        if zone_texts:
            lines += ["", "## Sensitive zones (handle carefully)"]
            lines += [f"- {z}" for z in zone_texts]
        out = "\n".join(lines)
        if to:
            Path(to).write_text(out)
            console.print(f"[green]✓[/green] Written to [bold]{to}[/bold]")
        else:
            console.print(out)
        return

    # ── Markdown (default) ───────────────────────────────────────────────────
    md_lines = [
        f"# Behavior card — {name}",
        "",
        f"| Field | Value |",
        f"|---|---|",
        f"| Fossil ID | `{fossil['id']}` |",
        f"| Type | {ftype} |",
        f"| Stability σ | {score_s} |",
        f"| Created | {created} |",
    ]
    if tags:
        md_lines.append(f"| Tags | {', '.join(tags)} |")
    if sig:
        md_lines += ["", "## Cognitive signature", "", f"> {sig}"]
    if src:
        md_lines += ["", "## Source prompt", "", "```", src, "```"]
    if inv_texts:
        md_lines += ["", "## Behavioral invariants", ""]
        md_lines += [f"- {i}" for i in inv_texts]
    if zone_texts:
        md_lines += ["", "## Sensitive zones", ""]
        md_lines += [f"- {z}" for z in zone_texts]
    md_lines += [
        "",
        "---",
        f"*Restored from Quark-AI fossil `{fossil['id'][:8]}` — quark-ai.cordee.ovh*",
    ]

    out = "\n".join(md_lines)

    if to:
        Path(to).write_text(out)
        console.print(f"[green]✓[/green] Behavior card written to [bold]{to}[/bold]")
        return

    # Print with syntax highlighting
    console.print()
    console.print(
        Panel.fit(
            f"[bold cyan]◈  Behavior card[/bold cyan]  [dim]{name}[/dim]",
            border_style="cyan",
        )
    )
    console.print(Syntax(out, "markdown", theme="monokai", word_wrap=True))
    console.print()
