#!/usr/bin/env python3
"""
ANALOG FRACTAL WORKBENCH 4.0
============================

Image-derived, evolving spectral library with batched residual atom fitting.

Features
--------
- RC-ladder-derived radial spectral generators
- Multi-stage whole-image residual reconstruction
- Batched matching pursuit with spatial non-maximum suppression
- Optional CuPy/CUDA acceleration; NumPy CPU fallback
- Shared RGB atom positions
- JSON model serialization and standalone decoding
- PNG snapshots: source, reconstruction, residual, fractal map
- Animated GIF showing reconstruction progress
- CSV performance metrics
- Live dashboard on http://127.0.0.1:8766
- Checkpointing and resumable output artifacts
- Actual accepted-atoms/second measurement against a 600 Hz target

Dependencies
------------
Required:
    py -m pip install numpy pillow

Optional NVIDIA GPU acceleration:
    py -m pip install cupy-cuda12x

Examples
--------
    py analog_fractal_workbench4.py photograph.jpg

    py analog_fractal_workbench4.py photograph.jpg ^
        --stages 16 --atoms-per-stage 512 --batch-size 64

    py analog_fractal_workbench4.py photograph.jpg ^
        --device cuda --max-side 768 --atoms-per-stage 1024

    py analog_fractal_workbench4.py --decode output\\image_fractal_model.json

Notes
-----
600 Hz is a measured target of 600 ACCEPTED atoms/second.
It is not a guaranteed hardware rate.

The fitting algorithm is batched approximate pursuit: atoms selected
within one batch are scored against the same correlation field. The
correlation field is then updated once for the complete batch.
This trades some sequential-greedy accuracy for throughput.

Convolution uses circular image boundaries.
"""

from __future__ import annotations

import argparse
import csv
import json
import math
import os
import sys
import time
import threading
import webbrowser
from dataclasses import dataclass
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
from typing import Any

import numpy as np
from PIL import Image, ImageDraw, ImageFont


VERSION = "4.0"
MODEL_FORMAT = "ANALOG-FRACTAL-WORKBENCH"
MODEL_VERSION = 4


# ---------------------------------------------------------------------------
# Optional CUDA backend
# ---------------------------------------------------------------------------

try:
    import cupy as cp

    CUDA_AVAILABLE = False
except Exception:
    cp = None
    CUDA_AVAILABLE = False


def choose_backend(device: str):
    if device == "cuda":
        if not CUDA_AVAILABLE:
            raise RuntimeError(
                "CUDA was requested, but CuPy/CUDA is unavailable. "
                "Install a CuPy build compatible with your CUDA runtime."
            )
        return cp, "cuda"

    if device == "cpu":
        return np, "cpu"

    if device == "auto" and CUDA_AVAILABLE:
        return cp, "cuda"

    return np, "cpu"


def to_numpy(value):
    if CUDA_AVAILABLE and cp is not None and isinstance(value, cp.ndarray):
        return cp.asnumpy(value)
    return np.asarray(value)


# ---------------------------------------------------------------------------
# Image utilities
# ---------------------------------------------------------------------------

def load_rgb(path: Path, max_side: int):
    image = Image.open(path).convert("RGB")
    original_size = image.size

    if max(image.size) > max_side:
        scale = max_side / max(image.size)
        new_size = (
            max(1, int(round(image.width * scale))),
            max(1, int(round(image.height * scale))),
        )
        image = image.resize(new_size, Image.Resampling.LANCZOS)

    array = np.asarray(image, dtype=np.float32) / 255.0

    return array, original_size, image.size


def save_rgb(array: np.ndarray, path: Path):
    image = np.clip(array, 0.0, 1.0)
    image = (image * 255.0 + 0.5).astype(np.uint8)
    Image.fromarray(image, mode="RGB").save(path)


def resize_rgb(array: np.ndarray, size: tuple[int, int]):
    image = Image.fromarray(
        np.clip(array * 255.0, 0, 255).astype(np.uint8),
        mode="RGB",
    )
    image = image.resize(size, Image.Resampling.LANCZOS)
    return np.asarray(image, dtype=np.float32) / 255.0


def residual_visual(residual: np.ndarray):
    """
    Convert signed residuals into a visible image:
      positive = brighter
      negative = darker
    """
    scale = float(np.percentile(np.abs(residual), 99.5))
    if scale < 1e-9:
        scale = 1.0

    visual = 0.5 + 0.5 * residual / scale
    return np.clip(visual, 0.0, 1.0)


def make_fractal_map(height: int, width: int, atoms: list[dict]):
    density = np.zeros((height, width), dtype=np.float32)

    for atom in atoms:
        y = int(atom["y"])
        x = int(atom["x"])
        density[y, x] += float(atom.get("score", 1.0))

    if density.max() > 0:
        density /= density.max()

    # A simple smooth display field; the underlying atom records remain exact.
    from PIL import ImageFilter

    img = Image.fromarray(
        (density * 255).astype(np.uint8), mode="L"
    )
    img = img.filter(ImageFilter.GaussianBlur(radius=2.0))
    smooth = np.asarray(img, dtype=np.float32) / 255.0

    rgb = np.stack(
        [
            np.clip(1.5 * smooth, 0, 1),
            np.clip(1.5 * (1.0 - np.abs(smooth - 0.5) * 2), 0, 1),
            np.clip(1.0 - smooth, 0, 1),
        ],
        axis=2,
    )

    return rgb


# ---------------------------------------------------------------------------
# RC ladder spectral generator
# ---------------------------------------------------------------------------

@dataclass
class Generator:
    stage: int
    rho: float
    gamma: float
    depth: int
    center: float
    bandwidth: float
    kernel_fft: np.ndarray
    kernel_energy: float


def radial_frequency_grid(height: int, width: int):
    fy = np.fft.fftfreq(height).astype(np.float32)
    fx = np.fft.rfftfreq(width).astype(np.float32)

    yy, xx = np.meshgrid(fy, fx, indexing="ij")
    radius = np.sqrt(xx * xx + yy * yy)

    return radius.astype(np.float32)


def rc_ladder_spectrum(
    radius: np.ndarray,
    rho: float,
    gamma: float,
    depth: int,
    center: float,
    bandwidth: float,
):
    """
    Construct a radial spectral response from a geometric RC ladder.

    Each ladder section contributes a first-order pole. The combined
    response is shaped into a smooth band-limited generator.
    """
    r = np.maximum(radius, 1e-7)

    response = np.ones_like(r, dtype=np.float64)

    for index in range(depth):
        resistance = rho ** index
        capacitance = gamma ** index
        tau = resistance * capacitance

        response /= np.sqrt(1.0 + (r * tau * 2.0 * math.pi) ** 2)

    log_r = np.log(r + 1e-9)
    log_center = math.log(max(center, 1e-8))

    band = np.exp(
        -0.5 * ((log_r - log_center) / max(bandwidth, 1e-4)) ** 2
    )

    # Suppress DC so that the kernel behaves as a detail generator.
    dc_suppression = r / (r + center * 0.08 + 1e-8)

    spectrum = response * band * dc_suppression
    spectrum[0, 0] = 0.0

    peak = float(np.max(np.abs(spectrum)))
    if peak > 0:
        spectrum /= peak

    return spectrum.astype(np.float32)


def make_generator(
    height: int,
    width: int,
    stage: int,
    stages: int,
    depth: int,
    rho: float,
    gamma: float,
):
    radius = radial_frequency_grid(height, width)

    # Progress from coarse structure toward finer detail.
    t = stage / max(1, stages - 1)
    center = 0.012 * ((0.42 / 0.012) ** t)
    bandwidth = 0.65 + 0.20 * t

    spectrum = rc_ladder_spectrum(
        radius=radius,
        rho=rho,
        gamma=gamma,
        depth=depth,
        center=center,
        bandwidth=bandwidth,
    )

    # Real radial spectrum -> real spatial kernel.
    kernel = np.fft.irfft2(spectrum, s=(height, width)).astype(np.float32)

    energy = float(np.sum(kernel * kernel))
    if energy <= 1e-20:
        raise RuntimeError("Generated an effectively zero-energy kernel.")

    # Keep the spectral transfer function and the kernel on a consistent scale.
    kernel /= math.sqrt(energy)
    kernel_fft = np.fft.rfft2(kernel).astype(np.complex64)
    kernel_energy = float(np.sum(np.abs(kernel_fft) ** 2) / (height * width))

    return Generator(
        stage=stage,
        rho=rho,
        gamma=gamma,
        depth=depth,
        center=center,
        bandwidth=bandwidth,
        kernel_fft=kernel_fft,
        kernel_energy=kernel_energy,
    )


# ---------------------------------------------------------------------------
# Batched atom fitting
# ---------------------------------------------------------------------------

def batched_atom_fit(
    residual: np.ndarray,
    kernel_fft_cpu: np.ndarray,
    max_atoms: int,
    threshold: float,
    batch_size: int,
    candidate_multiplier: int,
    min_distance: int,
    device: str,
    target_hz: int,
):
    """
    Batched shared-position RGB matching pursuit.

    Returns:
        atoms
        generated contribution
        metrics
    """
    xp, backend_name = choose_backend(device)

    start_time = time.perf_counter()

    residual_backend = xp.asarray(residual, dtype=xp.float32)
    kernel_fft = xp.asarray(kernel_fft_cpu, dtype=xp.complex64)

    height, width, channels = residual.shape
    pixel_count = height * width

    kernel_power = xp.abs(kernel_fft) ** 2
    kernel_energy = float(
        to_numpy(xp.sum(kernel_power)).reshape(()).item()
        / pixel_count
    )

    if kernel_energy <= 1e-20:
        raise RuntimeError("Kernel energy is too small for fitting.")

    # Correlation field: one channel per RGB component.
    residual_fft = xp.fft.rfft2(
        residual_backend, axes=(0, 1)
    )

    correlation_fft = (
        residual_fft * xp.conj(kernel_fft[:, :, None])
    )

    atoms: list[dict] = []
    batches = 0
    rejected = 0

    # Keep a CPU-side occupied map for straightforward NMS.
    occupied = np.zeros((height, width), dtype=np.bool_)

    while len(atoms) < max_atoms:
        batches += 1

        correlation = xp.fft.irfft2(
            correlation_fft,
            s=(height, width),
            axes=(0, 1),
        )

        # Shared RGB position score.
        score_map = xp.sqrt(
            xp.sum(correlation * correlation, axis=2)
        ) / kernel_energy

        flat = score_map.reshape(-1)

        wanted = min(
            int(batch_size * candidate_multiplier),
            pixel_count,
        )

        if wanted <= 0:
            break

        if wanted >= pixel_count:
            candidate_indices = xp.argsort(flat)[::-1]
        else:
            candidate_indices = xp.argpartition(
                flat, -wanted
            )[-wanted:]
            candidate_indices = candidate_indices[
                xp.argsort(flat[candidate_indices])[::-1]
            ]

        candidate_indices = to_numpy(candidate_indices).astype(
            np.int64, copy=False
        )
        candidate_scores = to_numpy(flat[candidate_indices]).astype(
            np.float64, copy=False
        )

        selected = []

        for flat_index, score in zip(
            candidate_indices, candidate_scores
        ):
            if score < threshold:
                break

            y = int(flat_index // width)
            x = int(flat_index % width)

            y0 = max(0, y - min_distance)
            y1 = min(height, y + min_distance + 1)
            x0 = max(0, x - min_distance)
            x1 = min(width, x + min_distance + 1)

            if occupied[y0:y1, x0:x1].any():
                rejected += 1
                continue

            selected.append((y, x, float(score)))
            occupied[y0:y1, x0:x1] = True

            if len(selected) >= min(
                batch_size, max_atoms - len(atoms)
            ):
                break

        if not selected:
            break

        ys = np.asarray([item[0] for item in selected], dtype=np.int64)
        xs = np.asarray([item[1] for item in selected], dtype=np.int64)

        ys_backend = xp.asarray(ys)
        xs_backend = xp.asarray(xs)

        # Extract RGB coefficients at selected locations.
        vectors = (
            correlation[ys_backend, xs_backend, :]
            / kernel_energy
        )

        vectors_cpu = to_numpy(vectors).astype(np.float32)

        # Build this batch's sparse impulse field.
        impulse_batch = xp.zeros(
            (height, width, channels), dtype=xp.float32
        )
        impulse_batch[ys_backend, xs_backend, :] = vectors

        # Exact correlation-field update for the complete batch.
        impulse_fft = xp.fft.rfft2(
            impulse_batch, axes=(0, 1)
        )

        correlation_fft -= (
            impulse_fft * kernel_power[:, :, None]
        )

        for index, (y, x, score) in enumerate(selected):
            rgb = vectors_cpu[index]

            atoms.append(
                {
                    "y": int(y),
                    "x": int(x),
                    "rgb": [
                        float(rgb[0]),
                        float(rgb[1]),
                        float(rgb[2]),
                    ],
                    "score": float(score),
                }
            )

        if len(atoms) >= max_atoms:
            break

    # Synthesize all accepted atoms in one convolution.
    impulses = np.zeros(
        (height, width, channels), dtype=np.float32
    )

    for atom in atoms:
        impulses[
            atom["y"], atom["x"], :
        ] += np.asarray(atom["rgb"], dtype=np.float32)

    impulses_backend = xp.asarray(impulses)

    generated_backend = xp.fft.irfft2(
        xp.fft.rfft2(impulses_backend, axes=(0, 1))
        * kernel_fft[:, :, None],
        s=(height, width),
        axes=(0, 1),
    )

    generated = to_numpy(generated_backend).astype(np.float32)

    elapsed = max(time.perf_counter() - start_time, 1e-9)
    rate = len(atoms) / elapsed

    metrics = {
        "backend": backend_name,
        "atoms": len(atoms),
        "batches": batches,
        "rejected_candidates": rejected,
        "seconds": elapsed,
        "atoms_per_second": rate,
        "target_hz": int(target_hz),
        "target_met": bool(rate >= target_hz),
        "kernel_energy": kernel_energy,
    }

    return atoms, generated, metrics


# ---------------------------------------------------------------------------
# Output and model functions
# ---------------------------------------------------------------------------

def write_json(path: Path, data: dict):
    temporary = path.with_suffix(path.suffix + ".tmp")

    with temporary.open("w", encoding="utf-8") as handle:
        json.dump(
            data,
            handle,
            ensure_ascii=False,
            separators=(",", ":"),
        )

    temporary.replace(path)


def save_metrics_csv(path: Path, rows: list[dict]):
    if not rows:
        return

    fields = [
        "stage",
        "atoms",
        "seconds",
        "atoms_per_second",
        "backend",
        "batches",
        "rejected_candidates",
        "residual_rms",
        "residual_max",
    ]

    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()

        for row in rows:
            writer.writerow(
                {key: row.get(key, "") for key in fields}
            )


def generator_model_record(generator: Generator):
    return {
        "stage": generator.stage,
        "rho": generator.rho,
        "gamma": generator.gamma,
        "depth": generator.depth,
        "center": generator.center,
        "bandwidth": generator.bandwidth,
    }


def save_model(
    path: Path,
    source_path: str,
    source_dimensions: tuple[int, int],
    analysis_dimensions: tuple[int, int],
    stages: list[dict],
    options: dict,
):
    model = {
        "format": MODEL_FORMAT,
        "version": MODEL_VERSION,
        "workbench_version": VERSION,
        "created_unix": time.time(),
        "source": str(source_path),
        "source_dimensions": list(source_dimensions),
        "analysis_dimensions": list(analysis_dimensions),
        "color_space": "RGB",
        "convolution": "circular",
        "fitting": "batched approximate matching pursuit",
        "options": options,
        "stages": stages,
    }

    write_json(path, model)


def decode_model(model_path: Path, output_path: Path):
    with model_path.open("r", encoding="utf-8") as handle:
        model = json.load(handle)

    if model.get("format") != MODEL_FORMAT:
        raise ValueError("Unrecognized model format.")

    width, height = model["analysis_dimensions"]
    reconstruction = np.zeros(
        (height, width, 3), dtype=np.float32
    )

    stages = model["stages"]
    total_atoms = 0

    for stage_record in stages:
        generator_record = stage_record["generator"]

        generator = make_generator(
            height=height,
            width=width,
            stage=int(generator_record["stage"]),
            stages=max(1, len(stages)),
            depth=int(generator_record["depth"]),
            rho=float(generator_record["rho"]),
            gamma=float(generator_record["gamma"]),
        )

        impulses = np.zeros(
            (height, width, 3), dtype=np.float32
        )

        for atom in stage_record["atoms"]:
            y = int(atom["y"])
            x = int(atom["x"])
            impulses[y, x, :] += np.asarray(
                atom["rgb"], dtype=np.float32
            )
            total_atoms += 1

        contribution = np.fft.irfft2(
            np.fft.rfft2(impulses, axes=(0, 1))
            * generator.kernel_fft[:, :, None],
            s=(height, width),
            axes=(0, 1),
        ).astype(np.float32)

        reconstruction += contribution

    output_path.mkdir(parents=True, exist_ok=True)

    save_rgb(
        np.clip(reconstruction, 0, 1),
        output_path / "decoded_reconstruction.png",
    )

    print()
    print("MODEL DECODE COMPLETE")
    print("---------------------")
    print(f"Stages:       {len(stages)}")
    print(f"Atoms:        {total_atoms:,}")
    print(f"Output:       {output_path / 'decoded_reconstruction.png'}")


# ---------------------------------------------------------------------------
# Animated snapshots
# ---------------------------------------------------------------------------

def make_stage_frame(
    source: np.ndarray,
    reconstruction: np.ndarray,
    stage: int,
    total_stages: int,
):
    source_img = Image.fromarray(
        np.clip(source * 255, 0, 255).astype(np.uint8),
        mode="RGB",
    )
    recon_img = Image.fromarray(
        np.clip(reconstruction * 255, 0, 255).astype(np.uint8),
        mode="RGB",
    )

    canvas = Image.new(
        "RGB",
        (source_img.width * 2, source_img.height + 36),
        (20, 20, 24),
    )

    canvas.paste(source_img, (0, 36))
    canvas.paste(recon_img, (source_img.width, 36))

    draw = ImageDraw.Draw(canvas)
    draw.text(
        (10, 10),
        f"ANALOG FRACTAL WORKBENCH 4.0 | STAGE {stage}/{total_stages}",
        fill=(245, 245, 245),
    )
    draw.text(
        (10, source_img.height + 18),
        "SOURCE",
        fill=(245, 245, 245),
    )
    draw.text(
        (source_img.width + 10, source_img.height + 18),
        "RECONSTRUCTION",
        fill=(245, 245, 245),
    )

    return canvas


def save_animation(frames: list[Image.Image], path: Path):
    if not frames:
        return

    frames[0].save(
        path,
        save_all=True,
        append_images=frames[1:],
        duration=350,
        loop=0,
        optimize=True,
    )


# ---------------------------------------------------------------------------
# Live dashboard
# ---------------------------------------------------------------------------

DASHBOARD_HTML = r"""
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="refresh" content="5">
<title>Analog Fractal Workbench 4.0</title>
<style>
body {
    background:#101216; color:#e8e8e8;
    font-family:Arial,sans-serif; margin:24px;
}
h1 {font-size:24px; margin-bottom:4px;}
small {color:#9da6b3;}
.grid {
    display:grid; grid-template-columns:repeat(2,minmax(280px,1fr));
    gap:16px; margin-top:20px;
}
.panel {
    background:#1b2028; padding:12px; border-radius:8px;
}
.panel img {width:100%; height:auto; display:block;}
.panel h3 {margin:4px 0 10px;}
pre {
    white-space:pre-wrap; overflow-wrap:anywhere;
    background:#1b2028; padding:14px; border-radius:8px;
}
@media(max-width:800px) {
    .grid {grid-template-columns:1fr;}
}
</style>
</head>
<body>
<h1>ANALOG FRACTAL WORKBENCH 4.0</h1>
<small>Automatically refreshes every five seconds</small>
<div class="grid">
<div class="panel"><h3>Source</h3><img src="source.png"></div>
<div class="panel"><h3>Reconstruction</h3><img src="reconstruction.png"></div>
<div class="panel"><h3>Residual</h3><img src="residual.png"></div>
<div class="panel"><h3>Atom field</h3><img src="fractal_map.png"></div>
</div>
<h2>Run status</h2>
<pre id="status">Loading status...</pre>
<script>
fetch("status.json?ts="+Date.now())
.then(r=>r.json())
.then(j=>document.getElementById("status").textContent =
    JSON.stringify(j,null,2))
.catch(e=>document.getElementById("status").textContent=String(e));
</script>
</body>
</html>
"""


def start_dashboard(output_dir: Path, host: str, port: int):
    (output_dir / "index.html").write_text(
        DASHBOARD_HTML, encoding="utf-8"
    )

    class QuietHandler(SimpleHTTPRequestHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(
                *args,
                directory=str(output_dir),
                **kwargs,
            )

        def log_message(self, fmt, *args):
            pass

    server = ThreadingHTTPServer((host, port), QuietHandler)

    thread = threading.Thread(
        target=server.serve_forever,
        daemon=True,
    )
    thread.start()

    return server


def update_dashboard_status(
    output_dir: Path,
    status: dict,
):
    write_json(output_dir / "status.json", status)


# ---------------------------------------------------------------------------
# Main fitting workflow
# ---------------------------------------------------------------------------

def run_workbench(args):
    input_path = Path(args.image).expanduser().resolve()

    if not input_path.exists():
        raise FileNotFoundError(input_path)

    output_dir = Path(args.output).expanduser().resolve()
    output_dir.mkdir(parents=True, exist_ok=True)

    print("=" * 78)
    print("ANALOG FRACTAL WORKBENCH 4.0")
    print("=" * 78)
    print(f"Input:          {input_path}")
    print(f"Output:         {output_dir}")
    print(f"Device request: {args.device}")
    print(f"Target rate:    {args.target_hz} accepted atoms/sec")
    print()

    source, original_size, analysis_size = load_rgb(
        input_path, args.max_side
    )

    height, width, _ = source.shape

    print(f"Original size:  {original_size[0]} x {original_size[1]}")
    print(f"Working size:   {width} x {height}")
    print(f"Stages:         {args.stages}")
    print(f"Atoms/stage:    {args.atoms_per_stage}")
    print(f"Batch size:     {args.batch_size}")
    print(f"CUDA available: {CUDA_AVAILABLE}")
    print()

    save_rgb(source, output_dir / "source.png")

    dashboard = None
    if args.dashboard:
        try:
            dashboard = start_dashboard(
                output_dir,
                args.dashboard_host,
                args.dashboard_port,
            )
            url = (
                f"http://{args.dashboard_host}:"
                f"{args.dashboard_port}/"
            )
            print(f"Dashboard:      {url}")

            if args.open_dashboard:
                webbrowser.open(url)

        except OSError as exc:
            print(f"Dashboard unavailable: {exc}")

    reconstruction = np.zeros_like(source)
    residual = source.copy()

    all_atoms = []
    stage_records = []
    metric_rows = []
    animation_frames = []

    total_start = time.perf_counter()
    total_atoms = 0

    for stage_index in range(args.stages):
        stage_number = stage_index + 1

        print()
        print("-" * 78)
        print(
            f"STAGE {stage_number:03d}/{args.stages:03d}"
        )
        print("-" * 78)

        generator = make_generator(
            height=height,
            width=width,
            stage=stage_index,
            stages=args.stages,
            depth=args.depth,
            rho=args.rho,
            gamma=args.gamma,
        )

        atoms, contribution, fit_metrics = batched_atom_fit(
            residual=residual,
            kernel_fft_cpu=generator.kernel_fft,
            max_atoms=args.atoms_per_stage,
            threshold=args.atom_threshold,
            batch_size=args.batch_size,
            candidate_multiplier=args.candidate_multiplier,
            min_distance=args.min_distance,
            device=args.device,
            target_hz=args.target_hz,
        )

        # Stage contribution is added to the reconstruction.
        reconstruction += contribution

        # Residual is always measured against the original source.
        residual = source - reconstruction

        total_atoms += len(atoms)

        for atom in atoms:
            atom["stage"] = stage_index

        all_atoms.extend(atoms)

        residual_rms = float(
            np.sqrt(np.mean(residual * residual))
        )
        residual_max = float(np.max(np.abs(residual)))

        row = {
            "stage": stage_number,
            "atoms": len(atoms),
            "seconds": fit_metrics["seconds"],
            "atoms_per_second": fit_metrics["atoms_per_second"],
            "backend": fit_metrics["backend"],
            "batches": fit_metrics["batches"],
            "rejected_candidates": fit_metrics[
                "rejected_candidates"
            ],
            "residual_rms": residual_rms,
            "residual_max": residual_max,
        }

        metric_rows.append(row)

        stage_record = {
            "generator": generator_model_record(generator),
            "atoms": atoms,
            "metrics": fit_metrics,
        }
        stage_records.append(stage_record)

        print(f"Backend:        {fit_metrics['backend']}")
        print(f"Accepted atoms: {len(atoms):,}")
        print(f"Batches:        {fit_metrics['batches']:,}")
        print(
            f"Fit time:       {fit_metrics['seconds']:.3f} sec"
        )
        print(
            "Atom rate:      "
            f"{fit_metrics['atoms_per_second']:.1f} atoms/sec"
        )
        print(
            f"600 Hz target:  "
            f"{'REACHED' if fit_metrics['target_met'] else 'NOT REACHED'}"
        )
        print(f"Residual RMS:   {residual_rms:.6f}")
        print(f"Residual max:   {residual_max:.6f}")

        # Current visual outputs.
        save_rgb(
            np.clip(reconstruction, 0, 1),
            output_dir / "reconstruction.png",
        )
        save_rgb(
            residual_visual(residual),
            output_dir / "residual.png",
        )
        save_rgb(
            make_fractal_map(height, width, all_atoms),
            output_dir / "fractal_map.png",
        )

        animation_frames.append(
            make_stage_frame(
                source,
                np.clip(reconstruction, 0, 1),
                stage_number,
                args.stages,
            )
        )

        # Save metrics and status after every stage.
        save_metrics_csv(
            output_dir / "metrics.csv",
            metric_rows,
        )

        elapsed_total = time.perf_counter() - total_start
        overall_rate = total_atoms / max(elapsed_total, 1e-9)

        status = {
            "version": VERSION,
            "state": "running",
            "stage": stage_number,
            "stages": args.stages,
            "total_atoms": total_atoms,
            "stage_atoms": len(atoms),
            "stage_rate_atoms_per_second": fit_metrics[
                "atoms_per_second"
            ],
            "overall_rate_atoms_per_second": overall_rate,
            "target_hz": args.target_hz,
            "backend": fit_metrics["backend"],
            "residual_rms": residual_rms,
            "elapsed_seconds": elapsed_total,
        }
        update_dashboard_status(output_dir, status)

        # Periodic model checkpoint.
        if (
            args.checkpoint_every > 0
            and stage_number % args.checkpoint_every == 0
        ):
            save_model(
                output_dir / "image_fractal_model_checkpoint.json",
                str(input_path),
                original_size,
                (width, height),
                stage_records,
                vars(args),
            )

        if args.stop_rms > 0 and residual_rms <= args.stop_rms:
            print(
                f"Early stop: residual RMS <= {args.stop_rms}"
            )
            break

    total_elapsed = time.perf_counter() - total_start
    overall_rate = total_atoms / max(total_elapsed, 1e-9)

    # Final output artifacts.
    reconstruction_clipped = np.clip(
        reconstruction, 0.0, 1.0
    )

    save_rgb(
        reconstruction_clipped,
        output_dir / "reconstruction.png",
    )
    save_rgb(
        residual_visual(source - reconstruction),
        output_dir / "residual.png",
    )
    save_rgb(
        make_fractal_map(height, width, all_atoms),
        output_dir / "fractal_map.png",
    )

    save_animation(
        animation_frames,
        output_dir / "reconstruction_progress.gif",
    )

    save_metrics_csv(
        output_dir / "metrics.csv",
        metric_rows,
    )

    save_model(
        output_dir / "image_fractal_model.json",
        str(input_path),
        original_size,
        (width, height),
        stage_records,
        vars(args),
    )

    final_status = {
        "version": VERSION,
        "state": "complete",
        "stages_completed": len(stage_records),
        "total_atoms": total_atoms,
        "elapsed_seconds": total_elapsed,
        "overall_atoms_per_second": overall_rate,
        "target_hz": args.target_hz,
        "target_met": overall_rate >= args.target_hz,
        "backend_requested": args.device,
        "cuda_available": CUDA_AVAILABLE,
        "residual_rms": float(
            np.sqrt(np.mean((source - reconstruction) ** 2))
        ),
        "files": [
            "source.png",
            "reconstruction.png",
            "residual.png",
            "fractal_map.png",
            "reconstruction_progress.gif",
            "metrics.csv",
            "image_fractal_model.json",
        ],
    }

    update_dashboard_status(output_dir, final_status)

    print()
    print("=" * 78)
    print("WORKBENCH COMPLETE")
    print("=" * 78)
    print(f"Stages completed: {len(stage_records)}")
    print(f"Total atoms:      {total_atoms:,}")
    print(f"Elapsed:          {total_elapsed:.2f} sec")
    print(f"Overall rate:     {overall_rate:.1f} atoms/sec")
    print(
        f"600 Hz target:    "
        f"{'REACHED' if overall_rate >= args.target_hz else 'NOT REACHED'}"
    )
    print()
    print("OUTPUT FILES")
    print("------------")

    for filename in final_status["files"]:
        file_path = output_dir / filename
        if file_path.exists():
            print(
                f"{filename:34s} "
                f"{file_path.stat().st_size / 1024:10.1f} KB"
            )

    print()
    print(f"Output directory: {output_dir}")

    if dashboard:
        print(
            "Dashboard:        "
            f"http://{args.dashboard_host}:{args.dashboard_port}/"
        )
        print("Dashboard remains active while this process runs.")

        if args.keep_dashboard:
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                pass

        dashboard.shutdown()


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def build_parser():
    parser = argparse.ArgumentParser(
        description=(
            "Analog Fractal Workbench 4.0 — "
            "batched spectral image reconstruction"
        ),
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument(
        "image",
        nargs="?",
        help="Input image",
    )

    parser.add_argument(
        "--output",
        default="analog_fractal_workbench4_output",
        help="Output directory",
    )

    parser.add_argument(
        "--decode",
        default=None,
        help="Decode an existing JSON model instead of fitting an image",
    )

    parser.add_argument("--stages", type=int, default=16)
    parser.add_argument("--atoms-per-stage", type=int, default=512)
    parser.add_argument("--batch-size", type=int, default=64)
    parser.add_argument("--candidate-multiplier", type=int, default=8)

    parser.add_argument("--max-side", type=int, default=512)
    parser.add_argument("--depth", type=int, default=8)

    parser.add_argument("--rho", type=float, default=1.61803398875)
    parser.add_argument("--gamma", type=float, default=0.61803398875)

    parser.add_argument(
        "--atom-threshold",
        type=float,
        default=0.012,
        help="Minimum normalized correlation score for accepting an atom",
    )

    parser.add_argument("--min-distance", type=int, default=2)

    parser.add_argument(
        "--device",
        choices=["auto", "cpu", "cuda"],
        default="auto",
    )

    parser.add_argument(
        "--target-hz",
        type=int,
        default=600,
        help="Target accepted atoms per second; measurement only",
    )

    parser.add_argument(
        "--stop-rms",
        type=float,
        default=0.0,
        help="Stop early when residual RMS falls below this value; 0 disables",
    )

    parser.add_argument(
        "--checkpoint-every",
        type=int,
        default=2,
        help="Write a model checkpoint every N stages; 0 disables",
    )

    parser.add_argument(
        "--dashboard",
        action=argparse.BooleanOptionalAction,
        default=True,
    )

    parser.add_argument(
        "--dashboard-host",
        default="127.0.0.1",
    )

    parser.add_argument(
        "--dashboard-port",
        type=int,
        default=8766,
    )

    parser.add_argument(
        "--open-dashboard",
        action="store_true",
    )

    parser.add_argument(
        "--keep-dashboard",
        action="store_true",
        help="Keep the dashboard server running after fitting completes",
    )

    return parser


def validate_args(args):
    if args.decode:
        return

    if not args.image:
        raise ValueError("Provide an input image or use --decode.")

    if args.stages < 1:
        raise ValueError("--stages must be at least 1.")

    if args.atoms_per_stage < 1:
        raise ValueError("--atoms-per-stage must be at least 1.")

    if args.batch_size < 1:
        raise ValueError("--batch-size must be at least 1.")

    if args.candidate_multiplier < 1:
        raise ValueError("--candidate-multiplier must be at least 1.")

    if args.max_side < 32:
        raise ValueError("--max-side must be at least 32.")

    if args.depth < 1:
        raise ValueError("--depth must be at least 1.")

    if args.min_distance < 0:
        raise ValueError("--min-distance cannot be negative.")

    if args.target_hz < 1:
        raise ValueError("--target-hz must be positive.")


def main():
    parser = build_parser()
    args = parser.parse_args()

    try:
        validate_args(args)

        if args.decode:
            decode_model(
                Path(args.decode).expanduser().resolve(),
                Path(args.output).expanduser().resolve(),
            )
        else:
            run_workbench(args)

    except KeyboardInterrupt:
        print("\nInterrupted by user.")
        return 130

    except Exception as exc:
        print()
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1

    return 0


if __name__ == "__main__":
    raise SystemExit(main())