#!/usr/bin/env python3
"""
ANALOG FRACTAL WORKBENCH 6.0 — CPU ONLY
======================================

Stable, bounded-coefficient, multistage spectral image reconstruction.

Workbench 6 corrects the coefficient overexposure in the previous batched
pursuit implementation. Candidate locations are still discovered in batches,
but coefficients are recalculated against the evolving correlation field
before each atom is committed. The correlation field is updated with the
kernel autocorrelation, so atoms within a batch cannot all spend the same
stale residual.

Properties
----------
- CPU only: no CUDA, CuPy, GPU detection, or GPU fallback
- RC-ladder-derived radial spectral generators
- Multistage residual reconstruction
- Sequentially corrected coefficients inside candidate batches
- Exact least-squares direction with conservative step-size shrinkage
- Optional coefficient magnitude guard
- Residual-energy descent check for every accepted atom
- Stage-level rollback if reconstruction energy does not decrease
- NaN/Inf/divergence detection and safe stop
- SciPy multithreaded FFT, with NumPy FFT fallback
- PNG source/reconstruction/residual/fractal-map snapshots
- Animated reconstruction GIF
- CSV stage metrics
- JSON model and independent decoder
- Periodic model checkpoints
- Live localhost dashboard

Install
-------
    py -m pip install numpy pillow scipy

Run
---
    py analog_fractal_workbench6.py photograph.jpg

Use all logical CPU workers:
    py analog_fractal_workbench6.py photograph.jpg --workers 0

More detailed run:
    py analog_fractal_workbench6.py photograph.jpg --workers 0 ^
        --max-side 768 --stages 16 --atoms-per-stage 512 ^
        --batch-size 32 --target-hz 600 --open-dashboard

Decode a saved model:
    py analog_fractal_workbench6.py --decode ^
        analog_fractal_workbench6_output/image_fractal_model.json

The target rate is a measurement, not a guarantee. Stability and valid
residual reduction take priority over the requested atom rate.

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

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

try:
    import scipy.fft as scipy_fft
    SCIPY_FFT_AVAILABLE = True
except Exception:
    scipy_fft = None
    SCIPY_FFT_AVAILABLE = False


VERSION = "6.0-CPU-STABLE"
MODEL_FORMAT = "ANALOG-FRACTAL-WORKBENCH"
MODEL_VERSION = 6
EPS = 1e-12

FFT_WORKERS = max(1, os.cpu_count() or 1)


# ---------------------------------------------------------------------------
# CPU FFT backend
# ---------------------------------------------------------------------------

def configure_fft_workers(workers: int) -> None:
    global FFT_WORKERS
    logical = max(1, os.cpu_count() or 1)
    FFT_WORKERS = logical if workers == 0 else max(1, min(workers, logical))


def fft_rfft2(array, axes=(0, 1)):
    if SCIPY_FFT_AVAILABLE:
        return scipy_fft.rfft2(array, axes=axes, workers=FFT_WORKERS)
    return np.fft.rfft2(array, axes=axes)


def fft_irfft2(array, s=None, axes=(0, 1)):
    if SCIPY_FFT_AVAILABLE:
        return scipy_fft.irfft2(array, s=s, axes=axes, workers=FFT_WORKERS)
    return np.fft.irfft2(array, s=s, axes=axes)


def fft_backend_name() -> str:
    return "SciPy FFT" if SCIPY_FFT_AVAILABLE else "NumPy FFT"


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

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

    if max(image.size) > max_side:
        scale = max_side / float(max(image.size))
        resized = (
            max(1, round(image.width * scale)),
            max(1, round(image.height * scale)),
        )
        image = image.resize(resized, 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) -> None:
    clean = np.nan_to_num(array, nan=0.0, posinf=1.0, neginf=0.0)
    pixels = (np.clip(clean, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8)
    Image.fromarray(pixels).save(path)


def residual_visual(residual: np.ndarray) -> np.ndarray:
    clean = np.nan_to_num(residual, nan=0.0, posinf=0.0, neginf=0.0)
    scale = float(np.percentile(np.abs(clean), 99.5))
    if not math.isfinite(scale) or scale < 1e-9:
        scale = 1.0
    return np.clip(0.5 + 0.5 * clean / scale, 0.0, 1.0)


def make_fractal_map(height: int, width: int, atoms: list[dict]) -> np.ndarray:
    density = np.zeros((height, width), dtype=np.float32)
    for atom in atoms:
        x = int(atom["x"])
        y = int(atom["y"])
        if 0 <= x < width and 0 <= y < height:
            density[y, x] += max(0.0, float(atom.get("score", 0.0)))

    maximum = float(density.max())
    if maximum > 0.0 and math.isfinite(maximum):
        density /= maximum

    gray = (density * 255.0).astype(np.uint8)
    image = Image.fromarray(gray).filter(ImageFilter.GaussianBlur(radius=2))
    smooth = np.asarray(image, dtype=np.float32) / 255.0

    return np.stack(
        (
            np.clip(1.5 * smooth, 0.0, 1.0),
            np.clip(1.5 * (1.0 - np.abs(smooth - 0.5) * 2.0), 0.0, 1.0),
            np.clip(1.0 - smooth, 0.0, 1.0),
        ),
        axis=2,
    )


def finite_stats(array: np.ndarray) -> tuple[float, float]:
    if not np.isfinite(array).all():
        return float("inf"), float("inf")
    rms = float(np.sqrt(np.mean(np.square(array, dtype=np.float64))))
    maximum = float(np.max(np.abs(array))) if array.size else 0.0
    return rms, maximum


# ---------------------------------------------------------------------------
# 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
    kernel_power: np.ndarray
    autocorrelation: np.ndarray


def radial_frequency_grid(height: int, width: int) -> np.ndarray:
    fy = np.fft.fftfreq(height).astype(np.float32)
    fx = np.fft.rfftfreq(width).astype(np.float32)
    yy, xx = np.meshgrid(fy, fx, indexing="ij")
    return np.sqrt(xx * xx + yy * yy).astype(np.float32)


def rc_ladder_spectrum(radius, rho, gamma, depth, center, bandwidth):
    r = np.maximum(radius.astype(np.float64), 1e-7)
    response = np.ones_like(r, dtype=np.float64)

    for index in range(depth):
        tau = (rho ** index) * (gamma ** index)
        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.0 and math.isfinite(peak):
        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,
):
    radius = radial_frequency_grid(height, width)
    spectrum = rc_ladder_spectrum(
        radius, rho, gamma, depth, center, bandwidth
    )

    kernel = fft_irfft2(
        spectrum, s=(height, width), axes=(0, 1)
    ).astype(np.float32)

    raw_energy = float(np.sum(kernel.astype(np.float64) ** 2))
    if not math.isfinite(raw_energy) or raw_energy <= 1e-20:
        raise RuntimeError("Generated an invalid or zero-energy kernel.")

    kernel /= math.sqrt(raw_energy)
    kernel_fft = fft_rfft2(kernel, axes=(0, 1)).astype(np.complex64)
    kernel_power = (
        kernel_fft.real * kernel_fft.real
        + kernel_fft.imag * kernel_fft.imag
    ).astype(np.float32)

    # Parseval: sum(|FFT(K)|^2)/N equals sum(K^2).
    pixel_count = height * width
    kernel_energy = float(
        np.sum(kernel_power, dtype=np.float64) / pixel_count
    )
    if not math.isfinite(kernel_energy) or kernel_energy <= 1e-12:
        raise RuntimeError("Kernel normalization failed.")

    # The autocorrelation lets us update the whole correlation field after
    # one atom without re-FFT'ing the residual for every atom.
    autocorrelation = fft_irfft2(
        kernel_power, s=(height, width), axes=(0, 1)
    ).astype(np.float32)

    if not np.isfinite(autocorrelation).all():
        raise RuntimeError("Kernel autocorrelation is not finite.")

    return (
        kernel,
        kernel_fft,
        kernel_energy,
        kernel_power,
        autocorrelation,
    )


def make_generator(height, width, stage, stages, depth, rho, gamma):
    t = stage / max(1, stages - 1)
    center = 0.012 * ((0.42 / 0.012) ** t)
    bandwidth = 0.65 + 0.20 * t

    kernel, kernel_fft, energy, power, autocorr = (
        make_kernel_from_parameters(
            height, width, rho, gamma, depth, center, bandwidth
        )
    )

    return Generator(
        stage=stage,
        rho=rho,
        gamma=gamma,
        depth=depth,
        center=center,
        bandwidth=bandwidth,
        kernel=kernel,
        kernel_fft=kernel_fft,
        kernel_energy=energy,
        kernel_power=power,
        autocorrelation=autocorr,
    )


# ---------------------------------------------------------------------------
# Stable sequentially-corrected batched matching pursuit
# ---------------------------------------------------------------------------

def batched_atom_fit(
    residual: np.ndarray,
    generator: Generator,
    max_atoms: int,
    threshold: float,
    batch_size: int,
    candidate_multiplier: int,
    min_distance: int,
    target_hz: int,
    step_size: float,
    max_coefficient: float,
):
    started = time.perf_counter()
    height, width, channels = residual.shape
    pixel_count = height * width

    if not np.isfinite(residual).all():
        raise FloatingPointError("Input residual contains NaN or infinity.")

    kernel_fft = generator.kernel_fft
    kernel_energy = generator.kernel_energy
    kernel_power = generator.kernel_power
    autocorrelation = generator.autocorrelation

    residual_fft = fft_rfft2(
        residual.astype(np.float32, copy=False), axes=(0, 1)
    )
    correlation_fft = (
        residual_fft * np.conj(kernel_fft[:, :, None])
    )
    correlation = fft_irfft2(
        correlation_fft, s=(height, width), axes=(0, 1)
    ).astype(np.float32)

    atoms: list[dict] = []
    occupied = np.zeros((height, width), dtype=np.bool_)
    batches = 0
    rejected = 0
    accepted_energy_gain = 0.0
    stop_reason = "atom limit"

    while len(atoms) < max_atoms:
        if not np.isfinite(correlation).all():
            stop_reason = "non-finite correlation"
            break

        batches += 1
        score_map = np.sqrt(
            np.sum(
                correlation.astype(np.float64) ** 2,
                axis=2,
                dtype=np.float64,
            )
        ) / kernel_energy

        if not np.isfinite(score_map).all():
            stop_reason = "non-finite candidate scores"
            break

        flat = score_map.reshape(-1)
        remaining = max_atoms - len(atoms)
        wanted = min(
            max(batch_size * candidate_multiplier, batch_size),
            pixel_count,
        )

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

        accepted_this_batch = 0

        for flat_index in candidate_indices:
            if len(atoms) >= max_atoms:
                break

            initial_score = float(flat[flat_index])
            if initial_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

            # Crucial Workbench 6 correction:
            # read the coefficient from the CURRENT correlation field,
            # after all previously accepted atoms have updated it.
            current_corr = correlation[y, x, :].astype(np.float64)
            current_score = float(
                np.linalg.norm(current_corr) / kernel_energy
            )

            if not math.isfinite(current_score) or current_score < threshold:
                rejected += 1
                continue

            coefficient = (
                current_corr / kernel_energy
            ) * float(step_size)

            # Safety bound on the RGB coefficient vector, not on the image.
            coefficient_norm = float(np.linalg.norm(coefficient))
            if max_coefficient > 0.0 and coefficient_norm > max_coefficient:
                coefficient *= max_coefficient / coefficient_norm

            # Exact predicted residual-energy change for this atom:
            # ΔE = -2<v,C> + ||v||² ||K||².
            gain = (
                2.0 * float(np.dot(coefficient, current_corr))
                - kernel_energy * float(np.dot(coefficient, coefficient))
            )

            if not math.isfinite(gain) or gain <= 1e-12:
                rejected += 1
                continue

            # Update correlation at every location using the shifted kernel
            # autocorrelation. np.roll implements circular boundaries.
            shifted_auto = np.roll(
                autocorrelation, shift=(y, x), axis=(0, 1)
            )
            correlation -= (
                shifted_auto[:, :, None]
                * coefficient.astype(np.float32)[None, None, :]
            )

            if not np.isfinite(correlation).all():
                stop_reason = "non-finite correlation after atom update"
                break

            rgb = coefficient.astype(np.float32)
            atoms.append({
                "y": y,
                "x": x,
                "rgb": [float(rgb[0]), float(rgb[1]), float(rgb[2])],
                "score": current_score,
            })
            occupied[y0:y1, x0:x1] = True
            accepted_energy_gain += gain
            accepted_this_batch += 1

            if accepted_this_batch >= min(batch_size, remaining):
                break

        if stop_reason.startswith("non-finite"):
            break
        if accepted_this_batch == 0:
            stop_reason = "no eligible candidates above threshold"
            break

    # Synthesize the stage from the exact stored atom coefficients.
    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
        )

    generated = fft_irfft2(
        fft_rfft2(impulses, axes=(0, 1))
        * kernel_fft[:, :, None],
        s=(height, width),
        axes=(0, 1),
    ).astype(np.float32)

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

    metrics = {
        "backend": "CPU",
        "fft_backend": fft_backend_name(),
        "workers": FFT_WORKERS if SCIPY_FFT_AVAILABLE else 1,
        "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,
        "predicted_energy_gain": accepted_energy_gain,
        "stop_reason": stop_reason,
        "step_size": float(step_size),
        "max_coefficient": float(max_coefficient),
    }

    return atoms, generated, metrics


# ---------------------------------------------------------------------------
# Model serialization and independent decoding
# ---------------------------------------------------------------------------

def write_json(path: Path, data: dict) -> None:
    temporary = path.with_suffix(path.suffix + ".tmp")
    with temporary.open("w", encoding="utf-8") as handle:
        json.dump(
            data, handle, ensure_ascii=False, separators=(",", ":"),
            allow_nan=False,
        )
    temporary.replace(path)


def generator_record(generator: Generator) -> dict:
    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,
    analysis_dimensions,
    stages,
    options,
):
    write_json(path, {
        "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": "sequentially corrected batched matching pursuit",
        "options": options,
        "stages": stages,
    })


def decode_model(model_path: Path, output_dir: Path) -> None:
    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 in model["stages"]:
        p = stage["generator"]
        _, kernel_fft, _, _, _ = make_kernel_from_parameters(
            height=height,
            width=width,
            rho=float(p["rho"]),
            gamma=float(p["gamma"]),
            depth=int(p["depth"]),
            center=float(p["center"]),
            bandwidth=float(p["bandwidth"]),
        )

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

        reconstruction += fft_irfft2(
            fft_rfft2(impulses, axes=(0, 1)) * kernel_fft[:, :, None],
            s=(height, width),
            axes=(0, 1),
        ).astype(np.float32)

    output_dir.mkdir(parents=True, exist_ok=True)
    save_rgb(reconstruction, output_dir / "decoded_reconstruction.png")

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


# ---------------------------------------------------------------------------
# GIF, CSV, and dashboard
# ---------------------------------------------------------------------------

def save_metrics_csv(path: Path, rows: list[dict]) -> None:
    fields = [
        "stage", "atoms", "seconds", "atoms_per_second",
        "fft_backend", "workers", "batches", "rejected_candidates",
        "residual_rms_before", "residual_rms_after",
        "residual_max_after", "energy_before", "energy_after",
        "stage_accepted", "stop_reason",
    ]
    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 make_stage_frame(source, reconstruction, stage, total_stages):
    src = Image.fromarray(
        (np.clip(source, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8)
    )
    rec = Image.fromarray(
        (np.clip(reconstruction, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8)
    )
    canvas = Image.new(
        "RGB", (src.width * 2, src.height + 36), (20, 20, 24)
    )
    canvas.paste(src, (0, 36))
    canvas.paste(rec, (src.width, 36))
    draw = ImageDraw.Draw(canvas)
    draw.text(
        (10, 10),
        f"ANALOG FRACTAL WORKBENCH 6.0 CPU | STAGE {stage}/{total_stages}",
        fill=(245, 245, 245),
    )
    draw.text((10, src.height + 18), "SOURCE", fill=(245, 245, 245))
    draw.text(
        (src.width + 10, src.height + 18),
        "RECONSTRUCTION",
        fill=(245, 245, 245),
    )
    return canvas


def save_animation(frames, path: Path) -> None:
    if frames:
        frames[0].save(
            path,
            save_all=True,
            append_images=frames[1:],
            duration=350,
            loop=0,
            optimize=True,
        )


DASHBOARD_HTML = r"""
<!doctype html>
<html><head><meta charset="utf-8">
<meta http-equiv="refresh" content="5">
<title>Analog Fractal Workbench 6.0 CPU</title>
<style>
body{background:#101216;color:#e8e8e8;font-family:Arial;margin:24px}
.grid{display:grid;grid-template-columns:repeat(2,minmax(280px,1fr));gap:16px}
.panel{background:#1b2028;padding:12px;border-radius:8px}
img{width:100%;height:auto;display:block}
pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#1b2028;padding:14px}
@media(max-width:800px){.grid{grid-template-columns:1fr}}
</style></head><body>
<h1>ANALOG FRACTAL WORKBENCH 6.0 — CPU</h1>
<p>Automatic refresh every five seconds.</p>
<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...</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


# ---------------------------------------------------------------------------
# Main workbench
# ---------------------------------------------------------------------------

def run_workbench(args) -> int:
    input_path = Path(args.image).expanduser().resolve()
    if not input_path.is_file():
        raise FileNotFoundError(
            f"Input image does not exist: {input_path}"
        )

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

    print("=" * 76)
    print("ANALOG FRACTAL WORKBENCH 6.0 — CPU ONLY / STABLE FIT")
    print("=" * 76)
    print(f"Input:          {input_path}")
    print(f"Output:         {output_dir}")
    print(f"FFT backend:    {fft_backend_name()}")
    print(f"CPU workers:    {FFT_WORKERS if SCIPY_FFT_AVAILABLE else 1}")
    print(f"Target:         {args.target_hz} accepted atoms/sec")
    print(f"Step size:      {args.step_size:.3f}")
    print(f"Coefficient cap:{args.max_coefficient:10.3f}")
    print("CUDA:           disabled")
    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("Coefficient update: sequential within each candidate batch")
    print("Residual guard:  atom-level descent + stage rollback")

    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}:{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: list[dict] = []
    stage_records: list[dict] = []
    metric_rows: list[dict] = []
    frames = []

    total_started = time.perf_counter()
    total_atoms = 0
    completed_normally = True
    stop_message = "completed requested stages"

    try:
        for stage_index in range(args.stages):
            stage_number = stage_index + 1
            print()
            print("-" * 76)
            print(f"STAGE {stage_number:03d}/{args.stages:03d}")
            print("-" * 76)

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

            before_rms, before_max = finite_stats(residual)
            energy_before = float(
                np.sum(residual.astype(np.float64) ** 2)
            )

            atoms, contribution, fit = batched_atom_fit(
                residual=residual,
                generator=generator,
                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,
                target_hz=args.target_hz,
                step_size=args.step_size,
                max_coefficient=args.max_coefficient,
            )

            # Validate the complete stage before committing it.
            candidate_residual = residual - contribution
            finite_stage = (
                np.isfinite(contribution).all()
                and np.isfinite(candidate_residual).all()
            )

            energy_after = (
                float(np.sum(candidate_residual.astype(np.float64) ** 2))
                if finite_stage else float("inf")
            )
            energy_tolerance = max(1e-10, energy_before * 1e-7)
            stage_accepted = (
                finite_stage
                and energy_after <= energy_before + energy_tolerance
            )

            if stage_accepted and energy_after > energy_before:
                # Tiny floating-point increase: reject rather than pretend
                # that it was an improvement.
                stage_accepted = False

            if stage_accepted:
                residual = candidate_residual.astype(np.float32, copy=False)
                reconstruction += contribution
                for atom in atoms:
                    atom["stage"] = stage_index
                all_atoms.extend(atoms)
                total_atoms += len(atoms)
            else:
                atoms = []
                fit["stop_reason"] = (
                    "stage rollback: invalid values or residual energy increased"
                )
                fit["atoms"] = 0
                fit["atoms_per_second"] = 0.0
                completed_normally = False
                stop_message = fit["stop_reason"]

            after_rms, after_max = finite_stats(residual)
            committed_energy = float(
                np.sum(residual.astype(np.float64) ** 2)
            )

            row = {
                "stage": stage_number,
                "atoms": len(atoms),
                "seconds": fit["seconds"],
                "atoms_per_second": fit["atoms_per_second"],
                "fft_backend": fit["fft_backend"],
                "workers": fit["workers"],
                "batches": fit["batches"],
                "rejected_candidates": fit["rejected_candidates"],
                "residual_rms_before": before_rms,
                "residual_rms_after": after_rms,
                "residual_max_after": after_max,
                "energy_before": energy_before,
                "energy_after": committed_energy,
                "stage_accepted": stage_accepted,
                "stop_reason": fit["stop_reason"],
            }
            metric_rows.append(row)

            if stage_accepted:
                stage_records.append({
                    "generator": generator_record(generator),
                    "atoms": atoms,
                    "metrics": fit,
                })

            print(f"FFT backend:    {fit['fft_backend']}")
            print(f"CPU workers:    {fit['workers']}")
            print(f"Accepted atoms: {len(atoms):,}")
            print(f"Batches:        {fit['batches']:,}")
            print(f"Fit time:       {fit['seconds']:.3f} sec")
            print(f"Atom rate:      {fit['atoms_per_second']:.1f} atoms/sec")
            print(f"Target:         {'REACHED' if fit['atoms_per_second'] >= args.target_hz else 'NOT REACHED'}")
            print(f"Residual RMS:   {before_rms:.6f} -> {after_rms:.6f}")
            print(f"Residual max:   {after_max:.6f}")
            print(f"Stage accepted: {'YES' if stage_accepted else 'NO — ROLLED BACK'}")
            print(f"Stop reason:    {fit['stop_reason']}")

            save_rgb(reconstruction, 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",
            )
            frames.append(make_stage_frame(
                source, reconstruction, stage_number, args.stages
            ))
            save_metrics_csv(output_dir / "metrics.csv", metric_rows)

            elapsed = time.perf_counter() - total_started
            overall_rate = total_atoms / max(elapsed, 1e-9)
            status = {
                "version": VERSION,
                "state": "running" if stage_accepted else "stopped_safely",
                "stage": stage_number,
                "stages": args.stages,
                "total_atoms": total_atoms,
                "stage_atoms": len(atoms),
                "stage_atoms_per_second": fit["atoms_per_second"],
                "overall_atoms_per_second": overall_rate,
                "target_hz": args.target_hz,
                "fft_backend": fit["fft_backend"],
                "cpu_workers": fit["workers"],
                "residual_rms": after_rms,
                "residual_max": after_max,
                "stage_accepted": stage_accepted,
                "stop_reason": fit["stop_reason"],
                "elapsed_seconds": elapsed,
            }
            write_json(output_dir / "status.json", status)

            if (
                stage_accepted
                and 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 not stage_accepted:
                break

            if fit["stop_reason"].startswith("non-finite"):
                completed_normally = False
                stop_message = fit["stop_reason"]
                break

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

    except KeyboardInterrupt:
        completed_normally = False
        stop_message = "interrupted by user"
        print("\nInterrupted. Saving the last committed reconstruction.")

    total_elapsed = time.perf_counter() - total_started
    overall_rate = total_atoms / max(total_elapsed, 1e-9)
    final_rms, final_max = finite_stats(source - reconstruction)

    # Always save the last committed, finite reconstruction.
    save_rgb(source, output_dir / "source.png")
    save_rgb(reconstruction, 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(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" if completed_normally else "stopped_safely",
        "stop_message": stop_message,
        "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,
        "fft_backend": fft_backend_name(),
        "cpu_workers": FFT_WORKERS if SCIPY_FFT_AVAILABLE else 1,
        "cuda": "disabled",
        "residual_rms": final_rms,
        "residual_max": final_max,
        "files": [
            "source.png",
            "reconstruction.png",
            "residual.png",
            "fractal_map.png",
            "reconstruction_progress.gif",
            "metrics.csv",
            "image_fractal_model.json",
        ],
    }
    write_json(output_dir / "status.json", final_status)

    print()
    print("=" * 76)
    print("WORKBENCH 6.0 COMPLETE")
    print("=" * 76)
    print(f"Stages committed: {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"Target:           {'REACHED' if overall_rate >= args.target_hz else 'NOT REACHED'}")
    print(f"Final residual:   RMS {final_rms:.6f} | max {final_max:.6f}")
    print(f"Run status:       {final_status['state']}")
    print(f"Reason:           {stop_message}")
    print()
    print("OUTPUT FILES")
    print("------------")
    for filename in final_status["files"]:
        file_path = output_dir / filename
        if file_path.exists():
            print(
                f"{filename:36s} "
                f"{file_path.stat().st_size / 1024:10.1f} KB"
            )
    print(f"\nOutput directory: {output_dir}")

    if dashboard:
        print(
            f"Dashboard: http://{args.dashboard_host}:{args.dashboard_port}/"
        )
        if args.keep_dashboard:
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                pass
        dashboard.shutdown()
        dashboard.server_close()

    return 0 if completed_normally else 2


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

def build_parser():
    parser = argparse.ArgumentParser(
        description="Analog Fractal Workbench 6.0 — CPU-only stable reconstruction",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument("image", nargs="?", help="Input image")
    parser.add_argument(
        "--output", default="analog_fractal_workbench6_output"
    )
    parser.add_argument("--decode", default=None)

    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=32)
    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(
        "--step-size",
        type=float,
        default=0.65,
        help="Conservative coefficient step; must be >0 and <=1",
    )
    parser.add_argument(
        "--max-coefficient",
        type=float,
        default=4.0,
        help="Maximum RGB coefficient-vector norm; 0 disables the cap",
    )

    parser.add_argument(
        "--workers",
        type=int,
        default=0,
        help="SciPy FFT workers; 0 means all logical CPUs",
    )
    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.")
    if args.workers < 0:
        raise ValueError("--workers must be 0 or positive.")
    if not (0.0 < args.step_size <= 1.0):
        raise ValueError("--step-size must be > 0 and <= 1.")
    if args.max_coefficient < 0:
        raise ValueError("--max-coefficient cannot be negative.")
    if args.atom_threshold < 0:
        raise ValueError("--atom-threshold cannot be negative.")
    if args.rho <= 0 or args.gamma <= 0:
        raise ValueError("--rho and --gamma must be positive.")


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()

    try:
        validate_args(args)
        configure_fft_workers(args.workers)

        if args.decode:
            decode_model(
                Path(args.decode).expanduser().resolve(),
                Path(args.output).expanduser().resolve(),
            )
            return 0

        return run_workbench(args)

    except KeyboardInterrupt:
        print("\nInterrupted by user.")
        return 130
    except Exception as exc:
        print(f"\nERROR: {exc}", file=sys.stderr)
        return 1


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