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

Complete integrated image-derived spectral reconstruction system.

FEATURES
--------
1. RC-ladder-derived radial spectral generators.
2. Multi-stage whole-image residual reconstruction.
3. Batched shared-RGB atom fitting.
4. Spatial non-maximum suppression.
5. Optional CuPy/CUDA acceleration.
6. Automatic NumPy CPU fallback.
7. Exact generator-parameter preservation in model files.
8. Standalone model decoder.
9. JSON model serialization.
10. PNG snapshots.
11. Animated reconstruction GIF.
12. CSV performance metrics.
13. Live dashboard on port 8766.
14. Periodic model checkpoints.
15. Actual accepted-atoms-per-second measurement.

INSTALL
-------
py -m pip install numpy pillow

Optional CUDA:
py -m pip install cupy-cuda12x

RUN
---
py analog_fractal_workbench4.py photograph.jpg

GPU:
py analog_fractal_workbench4.py photograph.jpg --device cuda

Benchmark:
py analog_fractal_workbench4.py photograph.jpg --device auto ^
    --max-side 512 --stages 16 --atoms-per-stage 1024 ^
    --batch-size 128 --target-hz 600 --open-dashboard

DECODE:
py analog_fractal_workbench4.py --decode ^
    analog_fractal_workbench4_output/image_fractal_model.json

600 Hz means 600 accepted atoms per second.
It is a measured performance target, not a guaranteed rate.

The pursuit algorithm is batched approximate matching pursuit:
all atoms in one batch are scored against the same correlation field.
The correlation field is then updated for the entire batch.

Convolution uses circular image boundaries.
"""

from __future__ import annotations

import argparse
import csv
import json
import math
import sys
import time
import threading
import webbrowser

from dataclasses import dataclass
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
from pathlib import Path

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


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 requested but CuPy/CUDA is unavailable. "
                "Install a CuPy package 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 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):
    array = np.clip(array, 0.0, 1.0)
    pixels = (array * 255.0 + 0.5).astype(np.uint8)

    Image.fromarray(pixels, mode="RGB").save(path)


def residual_visual(residual: np.ndarray):
    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()

    image = Image.fromarray(
        (density * 255).astype(np.uint8),
        mode="L",
    )

    image = image.filter(
        ImageFilter.GaussianBlur(radius=2.0)
    )

    smooth = np.asarray(
        image,
        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: np.ndarray
    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,
):
    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
    )

    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_kernel_from_parameters(
    height: int,
    width: int,
    rho: float,
    gamma: float,
    depth: int,
    center: float,
    bandwidth: float,
):
    """
    Deterministically rebuild a kernel from stored generator parameters.

    Used by both the fitting engine and model decoder.
    """

    radius = radial_frequency_grid(
        height,
        width,
    )

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

    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."
        )

    kernel /= math.sqrt(energy)

    kernel_fft = np.fft.rfft2(
        kernel
    ).astype(np.complex64)

    kernel_energy = float(
        np.sum(kernel * kernel)
    )

    return kernel, kernel_fft, kernel_energy


def make_generator(
    height: int,
    width: int,
    stage: int,
    stages: int,
    depth: int,
    rho: float,
    gamma: float,
):
    t = stage / max(1, stages - 1)

    center = 0.012 * (
        (0.42 / 0.012) ** t
    )

    bandwidth = 0.65 + 0.20 * t

    kernel, kernel_fft, kernel_energy = (
        make_kernel_from_parameters(
            height=height,
            width=width,
            rho=rho,
            gamma=gamma,
            depth=depth,
            center=center,
            bandwidth=bandwidth,
        )
    )

    return Generator(
        stage=stage,
        rho=rho,
        gamma=gamma,
        depth=depth,
        center=center,
        bandwidth=bandwidth,
        kernel=kernel,
        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.

    Correlation:
        C = inverse_fft(FFT(residual) * conjugate(FFT(kernel)))

    Coefficients:
        RGB = C[y,x,:] / kernel_energy

    Batched residual correlation update:
        C_fft -= FFT(impulse_batch) * abs(kernel_fft)^2

    All selected atoms in a batch use the same correlation field.
    """

    xp, backend_name = choose_backend(device)

    start_time = time.perf_counter()

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

    residual_backend = xp.asarray(
        residual,
        dtype=xp.float32,
    )

    kernel_fft = xp.asarray(
        kernel_fft_cpu,
        dtype=xp.complex64,
    )

    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."
        )

    residual_fft = xp.fft.rfft2(
        residual_backend,
        axes=(0, 1),
    )

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

    atoms = []
    occupied = np.zeros(
        (height, width),
        dtype=np.bool_,
    )

    batches = 0
    rejected = 0

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

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

        score_map = xp.sqrt(
            xp.sum(
                correlation * correlation,
                axis=2,
            )
        ) / kernel_energy

        flat = score_map.reshape(-1)

        wanted = min(
            batch_size * candidate_multiplier,
            pixel_count,
        )

        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 = []

        remaining = max_atoms - len(atoms)

        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,
                remaining,
            ):
                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)

        vectors = (
            correlation[
                ys_backend,
                xs_backend,
                :
            ] / kernel_energy
        )

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

        impulse_batch = xp.zeros(
            (height, width, channels),
            dtype=xp.float32,
        )

        impulse_batch[
            ys_backend,
            xs_backend,
            :
        ] = vectors

        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),
                }
            )

    # Synthesize the complete accepted atom set.
    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)

    # Synchronize CUDA before measuring elapsed time.
    if backend_name == "cuda":
        cp.cuda.Stream.null.synchronize()

    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


# ===========================================================================
# MODEL SERIALIZATION
# ===========================================================================

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 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_dir: 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."
        )

    if model.get("version") != MODEL_VERSION:
        raise ValueError(
            f"Unsupported model version: {model.get('version')}"
        )

    width, height = model["analysis_dimensions"]

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

    total_atoms = 0

    for stage_record in model["stages"]:
        record = stage_record["generator"]

        # Rebuild the exact generator parameters stored in the model.
        kernel, kernel_fft, kernel_energy = (
            make_kernel_from_parameters(
                height=height,
                width=width,
                rho=float(record["rho"]),
                gamma=float(record["gamma"]),
                depth=int(record["depth"]),
                center=float(record["center"]),
                bandwidth=float(record["bandwidth"]),
            )
        )

        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),
            )
            * kernel_fft[:, :, None],
            s=(height, width),
            axes=(0, 1),
        ).astype(np.float32)

        reconstruction += contribution

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

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

    print()
    print("=" * 72)
    print("MODEL DECODE COMPLETE")
    print("=" * 72)
    print(f"Stages: {len(model['stages'])}")
    print(f"Atoms:  {total_atoms:,}")
    print(
        f"Output: {output_dir / 'decoded_reconstruction.png'}"
    )


# ===========================================================================
# CSV METRICS
# ===========================================================================

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


def save_metrics_csv(
    path: Path,
    rows: list[dict],
):
    with path.open(
        "w",
        newline="",
        encoding="utf-8",
    ) as handle:
        writer = csv.DictWriter(
            handle,
            fieldnames=METRIC_FIELDS,
        )

        writer.writeheader()

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


# ===========================================================================
# GIF AND 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),
        (
            "ANALOG FRACTAL WORKBENCH 4.0"
            f" | 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,
    )


# ===========================================================================
# 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>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 WORKBENCH
# ===========================================================================

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} atoms/sec")
    print(f"CUDA available: {CUDA_AVAILABLE}")

    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}")

    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,
        )

        reconstruction += contribution
        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_records.append(
            {
                "generator": generator_model_record(
                    generator
                ),
                "atoms": atoms,
                "metrics": fit_metrics,
            }
        )

        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(
            "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}")

        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_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,
        )

        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)
    )

    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(
        "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}/"
        )

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

        dashboard.shutdown()


# ===========================================================================
# COMMAND LINE
# ===========================================================================

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",
    )

    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,
    )

    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,
    )

    parser.add_argument(
        "--stop-rms",
        type=float,
        default=0.0,
    )

    parser.add_argument(
        "--checkpoint-every",
        type=int,
        default=2,
    )

    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",
    )

    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(
            f"\nERROR: {exc}",
            file=sys.stderr,
        )
        return 1

    return 0


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