"""quark snapshot — capture a cognitive fossil from an agent."""
from __future__ import annotations

import json
import sys
import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich import box

from quark import config, client

console = Console()


def run(
    agent: str = typer.Option(
        "",
        "--agent", "-a",
        help="Agent name (overrides default_agent in config)",
    ),
    prompt: str = typer.Option(
        "",
        "--prompt", "-p",
        help="Source prompt or description of the agent's task",
    ),
    prompt_file: str = typer.Option(
        "",
        "--prompt-file", "-f",
        help="Read source prompt from a file",
    ),
    fossil_type: str = typer.Option(
        "cognitive_imprint",
        "--type",
        help="Fossil type: cognitive_imprint | behavioral_pattern | reasoning_trace",
    ),
    description: str = typer.Option("", "--description", "-d"),
    tags: str = typer.Option(
        "",
        "--tag",
        help="Comma-separated tags  e.g. --tag v1.2,production",
    ),
    mode: str = typer.Option(
        "pur",
        "--mode",
        help="Fossilization mode: pur (fast) | enrichi (deep)",
    ),
    output_json: bool = typer.Option(False, "--json", help="Output raw JSON"),
):
    """
    Capture a cognitive fossil — the behavioral fingerprint of an AI agent.

    The agent is observed across 7 calibrated probe angles. The result is
    a stable, versioned fossil stored in your Quark-AI repository.

    Examples:

      quark snapshot --agent gpt-4o --prompt "You are a customer support agent"

      quark snapshot --agent my_agent --prompt-file system_prompt.txt --tag v1.2

      echo "System prompt" | quark snapshot --agent my_agent
    """
    # Resolve agent name
    name = agent or config.get("default_agent") or ""
    if not name:
        name = typer.prompt("Agent name")

    # Resolve prompt
    src = prompt
    if not src and prompt_file:
        try:
            src = open(prompt_file).read().strip()
        except FileNotFoundError:
            console.print(f"[red]✗ File not found: {prompt_file}[/red]")
            raise typer.Exit(1)
    if not src and not sys.stdin.isatty():
        src = sys.stdin.read().strip()
    if not src:
        src = typer.prompt("Source prompt (describe the agent's role/task)")

    tag_list = [t.strip() for t in tags.split(",") if t.strip()]

    with console.status(
        f"[cyan]Observing [bold]{name}[/bold] across 7 cognitive probes…[/cyan]",
        spinner="dots",
    ):
        try:
            fossil = client.fossilize(
                name=name,
                source_prompt=src,
                fossil_type=fossil_type,
                description=description,
                tags=tag_list,
                mode=mode,
            )
        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(fossil))
        return

    fid   = fossil.get("id", "—")
    score = fossil.get("stability_score")
    score_str = f"{score:.3f}" 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"
    )

    invariants = fossil.get("behavioral_invariants") or []
    if isinstance(invariants, str):
        try:
            invariants = json.loads(invariants)
        except Exception:
            invariants = [invariants]

    sig = fossil.get("cognitive_signature", "")

    # ── Output panel ─────────────────────────────────────────────────────────
    console.print()
    console.print(
        Panel.fit(
            f"[bold cyan]◈  Fossil captured[/bold cyan]  "
            f"[dim]{fossil.get('name', name)}[/dim]",
            border_style="cyan",
        )
    )

    t = Table(box=box.SIMPLE, show_header=False, padding=(0, 1))
    t.add_column("key",   style="dim", width=22)
    t.add_column("value", style="bold")
    t.add_row("ID",            f"[dim]{fid}[/dim]")
    t.add_row("Stability σ",   f"[{score_color}]{score_str}[/{score_color}]")
    t.add_row("Type",          fossil.get("fossil_type", fossil_type))
    t.add_row("Mode",          mode)
    if tag_list:
        t.add_row("Tags",      ", ".join(tag_list))
    console.print(t)

    if sig:
        console.print(f"  [dim]Signature   [/dim][italic]{sig[:80]}{'…' if len(sig) > 80 else ''}[/italic]")

    if invariants:
        console.print()
        console.print("  [bold]Behavioral invariants[/bold]")
        for inv in invariants[:5]:
            text = inv.get("description", inv) if isinstance(inv, dict) else str(inv)
            console.print(f"  [dim]·[/dim] {text}")
        if len(invariants) > 5:
            console.print(f"  [dim]  … +{len(invariants)-5} more[/dim]")

    console.print()
    console.print(f"  [dim]quark diff <prev_id> {fid[:8]}…[/dim]")
    console.print()
