"""abreka exp show — full detail view of one experiment."""

from __future__ import annotations

import click
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.table import Table

from abreka.config import find_abreka_dir
from abreka.persistence import experiment_dir, load_experiment, normalize_exp_id
from abreka.runtime_costs import stage_ordered_keys


@click.command("show")
@click.argument("exp_id")
def show_cmd(exp_id: str):
    """Show full detail view of an experiment."""
    abreka_dir = find_abreka_dir()
    exp_id = normalize_exp_id(exp_id)
    exp = load_experiment(abreka_dir, exp_id)

    console = Console()

    # Header
    console.print(Panel(
        f"[bold]Experiment {exp.id}[/bold]  [{exp.status.value}]",
        title="Experiment Detail",
    ))

    # Metadata
    console.print(f"  [bold]Status:[/bold]     {exp.status.value}")
    console.print(f"  [bold]Created:[/bold]    {exp.created_at.isoformat()}")
    if exp.completed_at:
        console.print(f"  [bold]Completed:[/bold]  {exp.completed_at.isoformat()}")
    if exp.parents:
        console.print(f"  [bold]Parents:[/bold]    {', '.join(exp.parents)}")
    if exp.tags:
        console.print(f"  [bold]Tags:[/bold]       {', '.join(exp.tags)}")
    console.print()

    # Hypothesis & Method
    if exp.hypothesis:
        console.print(f"  [bold]Hypothesis:[/bold] {exp.hypothesis}")
    if exp.method:
        console.print(f"  [bold]Method:[/bold]     {exp.method}")
    console.print()

    # Metrics
    if exp.metrics:
        table = Table(title="Metrics", show_header=True, header_style="bold")
        table.add_column("Split")
        table.add_column("Metric")
        table.add_column("Value", justify="right")
        for split in sorted(exp.metrics):
            for key in sorted(exp.metrics[split]):
                table.add_row(split, key, f"{exp.metrics[split][key]:.6f}")
        console.print(table)
        console.print()

    # Runtime costs
    if exp.runtime_costs:
        runtime_table = Table(title="Runtime Costs", show_header=True, header_style="bold")
        runtime_table.add_column("Stage")
        runtime_table.add_column("Attempts", justify="right")
        runtime_table.add_column("Total (s)", justify="right")
        runtime_table.add_column("Last (s)", justify="right")
        runtime_table.add_column("Last Status")

        total_runtime = 0.0
        for stage in stage_ordered_keys(exp.runtime_costs):
            info = exp.runtime_costs.get(stage, {})
            if not isinstance(info, dict):
                continue
            try:
                attempts = int(info.get("attempts", 0) or 0)
            except (TypeError, ValueError):
                attempts = 0
            try:
                total = float(info.get("seconds_total", 0.0) or 0.0)
            except (TypeError, ValueError):
                total = 0.0
            try:
                last = float(info.get("seconds_last", 0.0) or 0.0)
            except (TypeError, ValueError):
                last = 0.0
            status = str(info.get("last_status", ""))
            total_runtime += total
            runtime_table.add_row(stage, str(attempts), f"{total:.2f}", f"{last:.2f}", status)

        runtime_table.caption = f"Total runtime: {total_runtime:.2f}s"
        console.print(runtime_table)
        console.print()

    # Failure reason
    if exp.failure_reason:
        console.print(f"  [bold red]Failure:[/bold red] {exp.failure_reason}")
        console.print()

    # Findings
    findings_path = experiment_dir(abreka_dir, exp_id) / "findings.md"
    if findings_path.is_file():
        content = findings_path.read_text()
        if content.strip():
            console.print("[bold]Findings:[/bold]")
            console.print(Markdown(content))
