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

ACCELERATED WHOLE-IMAGE ATOM DISCOVERY

Core architecture:
    - Geometric series-R / shunt-C ladder kernels.
    - Continuous radial spatial-frequency response.
    - Whole-image spectral analysis.
    - Sparse translated impulse fields.
    - Shared RGB atom positions.
    - Incremental correlation matching pursuit.
    - Batched FFT reconstruction.
    - Cached generator kernels.
    - Progressive residual fitting.
    - Compressed JSON model.
    - Live local dashboard.
    - PNG stage snapshots.
    - Detailed performance profiling.

Major optimization:
    Initial correlation:
        FFT(residual) * conjugate(FFT(kernel))

    Subsequent atom selections:
        correlation -= shifted_autocorrelation * RGB_coefficient

    No repeated image FFT per atom.

Dependencies:
    py -m pip install numpy pillow

Run:
    py analog_fractal_workbench3.py photograph.jpg

Recommended initial test:
    py analog_fractal_workbench3.py photograph.jpg ^
        --stages 16 ^
        --bins 192 ^
        --atoms-per-stage 256 ^
        --max-candidates 160 ^
        --max-side 512

Dashboard:
    http://127.0.0.1:8766
"""

from __future__ import annotations

import argparse
import base64
import io
import json
import math
import os
import threading
import time
import zlib

from fractions import Fraction
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

import numpy as np
from PIL import Image


VERSION = "ANALOG-FRACTAL-3.0"

STATE_LOCK = threading.RLock()

STATE = {
    "status": "starting",
    "message": "Initializing",
    "stage": 0,
    "stages": 0,
    "mse": None,
    "model_bytes": 0,
    "elapsed": 0.0,
    "history": [],
    "original": None,
    "reconstruction": None,
    "residual": None,
    "spectrum": None,
    "atoms_total": 0,
    "discovery_seconds": 0.0,
    "matching_seconds": 0.0,
    "synthesis_seconds": 0.0,
}


def update_state(**kwargs):
    with STATE_LOCK:
        STATE.update(kwargs)


# ============================================================
# IMAGE
# ============================================================

def load_image(filename, max_side):
    image = Image.open(filename).convert("RGB")
    original_size = image.size

    scale = min(1.0, max_side / max(image.size))

    if scale < 1.0:
        image = image.resize(
            (
                max(1, round(image.width * scale)),
                max(1, round(image.height * scale)),
            ),
            Image.Resampling.LANCZOS,
        )

    return np.asarray(image, dtype=np.float64) / 255.0, original_size


def mse(a, b):
    return float(np.mean((a - b) ** 2))


def display_image(array, max_side=640):
    array = np.asarray(array, dtype=np.float64)

    if array.ndim == 2:
        array = np.repeat(array[:, :, None], 3, axis=2)

    array = np.clip(array, 0.0, 1.0)

    image = Image.fromarray((array * 255).astype(np.uint8))

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

    buf = io.BytesIO()
    image.save(buf, format="JPEG", quality=80)

    return "data:image/jpeg;base64," + base64.b64encode(
        buf.getvalue()
    ).decode("ascii")


def normalized_display(array):
    array = np.asarray(array, dtype=np.float64)

    low = float(np.min(array))
    high = float(np.max(array))

    if high - low < 1e-14:
        return np.zeros_like(array)

    return (array - low) / (high - low)


# ============================================================
# EXACT RATIO IDENTITIES
# ============================================================

def exact_ratios():
    values = [
        "1.125",
        "1.2",
        "1.25",
        "1.3333333333333333",
        "1.5",
        "1.6666666666666667",
        "1.75",
        "2",
        "2.25",
        "2.5",
        "3",
    ]

    return sorted(set(Fraction(x) for x in values))


def candidate_families():
    ratios = exact_ratios()
    result = []

    for rho in ratios:
        for gamma in ratios:

            if rho <= 1 or gamma <= 1:
                continue

            rf = float(rho)
            gf = float(gamma)

            for n in (3, 4, 5, 6, 8, 10, 12):

                result.append({
                    "rho_num": rho.numerator,
                    "rho_den": rho.denominator,
                    "gamma_num": gamma.numerator,
                    "gamma_den": gamma.denominator,
                    "rho": rf,
                    "gamma": gf,
                    "n": n,
                    "alpha": math.log(rf) / math.log(rf * gf),
                })

    return result


# ============================================================
# GEOMETRIC RC LADDER
# ============================================================

def ladder_impedance(frequencies, rho, gamma, n):

    s = 1j * np.asarray(frequencies, dtype=np.float64)

    s = np.where(
        np.abs(s) < 1e-12,
        1e-12 + 0j,
        s,
    )

    k = n - 1

    z = rho ** k + 1.0 / (s * gamma ** k)

    for k in range(n - 2, -1, -1):

        resistance = rho ** k
        capacitance = gamma ** k

        z = resistance + 1.0 / (
            s * capacitance + 1.0 / z
        )

    return z


def ladder_response(radius, family):

    f = np.maximum(
        np.asarray(radius, dtype=np.float64),
        1e-5,
    )

    z = ladder_impedance(
        f,
        family["rho"],
        family["gamma"],
        family["n"],
    )

    reference_frequency = float(np.median(f))

    zref = ladder_impedance(
        np.array([reference_frequency]),
        family["rho"],
        family["gamma"],
        family["n"],
    )[0]

    magnitude = np.maximum(
        np.abs(z / zref),
        1e-12,
    )

    magnitude /= np.median(magnitude)

    return magnitude


# ============================================================
# SPATIAL FREQUENCY GRID
# ============================================================

def frequency_grid(height, width):

    fy = np.fft.fftfreq(height)
    fx = np.fft.rfftfreq(width)

    yy, xx = np.meshgrid(
        fy,
        fx,
        indexing="ij",
    )

    return np.sqrt(xx * xx + yy * yy)


def radial_bin_data(radius, bins):

    maximum = float(np.max(radius))

    edges = np.linspace(
        0.0,
        maximum + 1e-12,
        bins + 1,
    )

    index = np.digitize(
        radius.ravel(),
        edges,
    ) - 1

    index = np.clip(index, 0, bins - 1)

    counts = np.bincount(
        index,
        minlength=bins,
    ).astype(np.float64)

    centers = (edges[:-1] + edges[1:]) * 0.5

    return centers, index, counts


def radial_average(values, index, counts, bins):

    sums = np.bincount(
        index,
        weights=np.asarray(values).ravel(),
        minlength=bins,
    )

    return sums / np.maximum(counts, 1.0)


# ============================================================
# ACCELERATED SPECTRAL DISCOVERY
# ============================================================

def family_spectral_error(
    family,
    target_power,
    radial_centers,
):

    # The ladder is radially symmetric.
    # There is no need to evaluate its response at every
    # image frequency coordinate.

    response = ladder_response(
        radial_centers,
        family,
    )

    predicted = response * response

    valid = (
        (target_power > 1e-12)
        & (predicted > 1e-12)
    )

    if np.count_nonzero(valid) < 8:
        return float("inf")

    a = np.log(target_power[valid])
    b = np.log(predicted[valid])

    b += np.mean(a - b)

    return float(np.mean((a - b) ** 2))


def discover_best_family(
    residual,
    families,
    bins,
    grid_data=None,
):

    height, width, channels = residual.shape

    if grid_data is None:

        radius = frequency_grid(height, width)

        centers, index, counts = radial_bin_data(
            radius,
            bins,
        )

    else:

        centers, index, counts = grid_data

    spectrum = np.fft.rfft2(
        residual,
        axes=(0, 1),
    )

    power = np.mean(
        np.abs(spectrum) ** 2,
        axis=2,
    )

    target_power = radial_average(
        power,
        index,
        counts,
        bins,
    )

    best = None
    best_error = float("inf")

    total = len(families)

    for i, family in enumerate(families):

        error = family_spectral_error(
            family,
            target_power,
            centers,
        )

        if error < best_error:
            best_error = error
            best = family

        if i % 32 == 0:

            update_state(
                message=f"Spectral discovery {i + 1}/{total}"
            )

    return best, best_error, centers, target_power


# ============================================================
# GENERATOR KERNEL
# ============================================================

def make_generator(family, shape):

    height, width, _ = shape

    radius = frequency_grid(height, width)

    response = ladder_response(
        radius,
        family,
    )

    response[0, 0] = 0.0

    kernel = np.fft.irfft2(
        response,
        s=(height, width),
    )

    norm = float(
        np.sqrt(np.sum(kernel * kernel))
    )

    if norm < 1e-14:
        raise ValueError("Degenerate generator kernel")

    kernel /= norm

    kernel_fft = np.fft.rfft2(kernel)

    return kernel_fft, kernel


# ============================================================
# ACCELERATED MATCHING PURSUIT
# ============================================================

def sparse_impulse_fit(
    residual,
    kernel_fft,
    max_atoms=256,
    threshold=0.012,
):

    """
    Incremental whole-image matching pursuit.

    Expensive operations:
        Initial correlation FFT.
        Initial kernel autocorrelation FFT.

    Subsequent atom selections:
        Array multiplication and reduction.
        No repeated residual FFT.
        No repeated kernel roll.
        No repeated full-image synthesis.

    Atom positions remain shared across RGB.
    """

    height, width, channels = residual.shape

    kernel_energy = float(
        np.sum(np.abs(kernel_fft) ** 2)
        / (height * width)
    )

    if kernel_energy < 1e-16:
        return [], np.zeros_like(residual)

    # --------------------------------------------------------
    # Initial RGB correlation
    # --------------------------------------------------------

    residual_fft = np.fft.rfft2(
        residual,
        axes=(0, 1),
    )

    correlation = np.fft.irfft2(
        residual_fft * np.conj(kernel_fft)[:, :, None],
        s=(height, width),
        axes=(0, 1),
    )

    # --------------------------------------------------------
    # Kernel autocorrelation
    # --------------------------------------------------------

    autocorrelation = np.fft.irfft2(
        np.abs(kernel_fft) ** 2,
        s=(height, width),
    )

    # --------------------------------------------------------
    # Sparse impulse coefficient field
    # --------------------------------------------------------

    impulses = np.zeros(
        (height, width, channels),
        dtype=np.float64,
    )

    atoms = []

    for atom_index in range(max_atoms):

        # One score per spatial position.
        score = np.sum(
            correlation * correlation,
            axis=2,
        )

        flat_index = int(np.argmax(score))

        y, x = np.unravel_index(
            flat_index,
            score.shape,
        )

        vector = correlation[y, x, :] / kernel_energy

        improvement = float(
            np.sum(correlation[y, x, :] ** 2)
            / kernel_energy
        )

        if not np.isfinite(improvement):
            break

        if improvement < threshold:
            break

        impulses[y, x, :] += vector

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

        # ----------------------------------------------------
        # Incremental correlation update
        # ----------------------------------------------------

        shifted_auto = np.roll(
            autocorrelation,
            shift=(int(y), int(x)),
            axis=(0, 1),
        )

        correlation -= (
            shifted_auto[:, :, None]
            * vector[None, None, :]
        )

        if atom_index % 32 == 0:

            update_state(
                message=(
                    f"Accelerated atom discovery: "
                    f"{atom_index + 1}/{max_atoms}"
                )
            )

    # --------------------------------------------------------
    # Batched synthesis
    # --------------------------------------------------------

    if not atoms:
        return atoms, np.zeros_like(residual)

    impulse_fft = np.fft.rfft2(
        impulses,
        axes=(0, 1),
    )

    generated = np.fft.irfft2(
        impulse_fft * kernel_fft[:, :, None],
        s=(height, width),
        axes=(0, 1),
    )

    return atoms, generated


# ============================================================
# MODEL RENDERING
# ============================================================

def render_atoms(atoms, kernel, shape):

    height, width, channels = shape

    impulses = np.zeros(
        (height, width, channels),
        dtype=np.float64,
    )

    for atom in atoms:

        y = int(atom["y"])
        x = int(atom["x"])

        impulses[y, x, :] += np.asarray(
            atom["rgb"],
            dtype=np.float64,
        )

    return np.fft.irfft2(
        np.fft.rfft2(impulses, axes=(0, 1))
        * np.fft.rfft2(kernel)[:, :, None],
        s=(height, width),
        axes=(0, 1),
    )


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

def save_model(model, filename, level=6):

    raw = json.dumps(
        model,
        separators=(",", ":"),
        ensure_ascii=False,
    ).encode("utf-8")

    compressed = zlib.compress(
        raw,
        level=level,
    )

    path = Path(filename)
    path.parent.mkdir(parents=True, exist_ok=True)

    temporary = path.with_suffix(path.suffix + ".tmp")

    with open(temporary, "wb") as f:
        f.write(compressed)

    os.replace(temporary, path)

    return len(compressed)


# ============================================================
# DASHBOARD
# ============================================================

HTML = r"""
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Analog Fractal Workbench 3.0</title>
<style>
body {
    margin:0;
    padding:22px;
    background:#101318;
    color:#e8edf4;
    font-family:Segoe UI,Arial,sans-serif;
}
h1 {font-size:22px;margin:0 0 5px}
small {color:#98a5b5}
.status {margin:16px 0;color:#b8c9da}
.grid {
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
    gap:14px;
}
.panel {
    background:#1a2029;
    border:1px solid #303947;
    border-radius:8px;
    padding:12px;
    min-width:0;
}
.panel h2 {font-size:14px;margin:0 0 10px}
img {
    width:100%;
    display:block;
    background:#080a0d;
    min-height:120px;
    object-fit:contain;
}
.metrics {
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:10px;
    margin:14px 0;
}
.metric {
    background:#1a2029;
    border:1px solid #303947;
    border-radius:7px;
    padding:12px;
}
.metric b {
    display:block;
    font-size:19px;
    margin-top:5px;
}
.metric span {color:#9aa9ba;font-size:11px}
table {width:100%;border-collapse:collapse;margin-top:14px}
td,th {
    text-align:left;
    padding:7px;
    border-bottom:1px solid #303947;
    font-size:12px;
}
th {color:#9aa9ba}
@media(max-width:800px) {
    .grid {grid-template-columns:1fr}
    .metrics {grid-template-columns:repeat(2,1fr)}
}
</style>
</head>
<body>

<h1>Analog Fractal Workbench 3.0</h1>
<small>Incremental correlation · geometric RC ladders · sparse whole-image synthesis</small>

<div class="status" id="status">Connecting...</div>

<div class="metrics">
<div class="metric"><span>Stage</span><b id="stage">0</b></div>
<div class="metric"><span>Whole-image MSE</span><b id="mse">—</b></div>
<div class="metric"><span>Model bytes</span><b id="bytes">—</b></div>
<div class="metric"><span>Elapsed</span><b id="elapsed">—</b></div>
<div class="metric"><span>Total atoms</span><b id="atoms">0</b></div>
<div class="metric"><span>Discovery</span><b id="discovery">0s</b></div>
<div class="metric"><span>Matching</span><b id="matching">0s</b></div>
<div class="metric"><span>Synthesis</span><b id="synthesis">0s</b></div>
</div>

<div class="grid">
<div class="panel"><h2>Original</h2><img id="original"></div>
<div class="panel"><h2>Analog reconstruction</h2><img id="reconstruction"></div>
<div class="panel"><h2>Continuous residual field</h2><img id="residual"></div>
<div class="panel"><h2>Radial ladder kernel</h2><img id="spectrum"></div>
</div>

<div class="panel" style="margin-top:14px">
<h2>Generator history</h2>
<table>
<thead><tr>
<th>Stage</th><th>rho</th><th>gamma</th><th>n</th>
<th>alpha</th><th>atoms</th><th>MSE</th>
<th>Spectral error</th><th>Seconds</th>
</tr></thead>
<tbody id="history"></tbody>
</table>
</div>

<script>
async function refresh() {
    try {
        const r = await fetch('/state');
        const s = await r.json();

        document.getElementById('status').textContent =
            s.message + ' · ' + s.status;

        document.getElementById('stage').textContent =
            s.stage + '/' + s.stages;

        document.getElementById('mse').textContent =
            s.mse === null ? '—' : Number(s.mse).toFixed(7);

        document.getElementById('bytes').textContent =
            s.model_bytes ?? '—';

        document.getElementById('elapsed').textContent =
            Number(s.elapsed || 0).toFixed(1) + 's';

        document.getElementById('atoms').textContent =
            s.atoms_total ?? 0;

        document.getElementById('discovery').textContent =
            Number(s.discovery_seconds || 0).toFixed(2) + 's';

        document.getElementById('matching').textContent =
            Number(s.matching_seconds || 0).toFixed(2) + 's';

        document.getElementById('synthesis').textContent =
            Number(s.synthesis_seconds || 0).toFixed(2) + 's';

        for (const key of [
            'original','reconstruction','residual','spectrum'
        ]) {
            if (s[key]) {
                const el = document.getElementById(key);
                if (el.src !== s[key]) el.src = s[key];
            }
        }

        document.getElementById('history').innerHTML =
            s.history.map(h => `<tr>
                <td>${h.stage}</td>
                <td>${h.rho.toFixed(5)}</td>
                <td>${h.gamma.toFixed(5)}</td>
                <td>${h.n}</td>
                <td>${h.alpha.toFixed(4)}</td>
                <td>${h.atoms}</td>
                <td>${h.mse.toFixed(7)}</td>
                <td>${h.spectral_error.toExponential(3)}</td>
                <td>${h.seconds.toFixed(2)}</td>
            </tr>`).join('');

    } catch(e) {
        document.getElementById('status').textContent =
            'Dashboard connection error: ' + e;
    }
}

setInterval(refresh,1000);
refresh();
</script>
</body>
</html>
"""


def start_dashboard(port):

    class Handler(BaseHTTPRequestHandler):

        def do_GET(self):

            if self.path == "/":

                data = HTML.encode("utf-8")

                self.send_response(200)
                self.send_header(
                    "Content-Type",
                    "text/html; charset=utf-8",
                )
                self.send_header(
                    "Content-Length",
                    str(len(data)),
                )
                self.end_headers()
                self.wfile.write(data)

                return

            if self.path == "/state":

                with STATE_LOCK:
                    snapshot = dict(STATE)

                data = json.dumps(snapshot).encode("utf-8")

                self.send_response(200)
                self.send_header(
                    "Content-Type",
                    "application/json",
                )
                self.send_header(
                    "Content-Length",
                    str(len(data)),
                )
                self.end_headers()
                self.wfile.write(data)

                return

            self.send_error(404)

        def log_message(self, *args):
            pass

    server = ThreadingHTTPServer(
        ("127.0.0.1", port),
        Handler,
    )

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

    thread.start()

    return server


# ============================================================
# ENGINE
# ============================================================

def run(args):

    started = time.time()

    source = Path(args.image)

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

    original, original_size = load_image(
        str(source),
        args.max_side,
    )

    height, width, channels = original.shape

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

    families = candidate_families()

    if args.max_candidates > 0:
        families = families[:args.max_candidates]

    model = {
        "version": VERSION,
        "source": source.name,
        "source_dimensions": list(original_size),
        "analysis_dimensions": [width, height],
        "generator_type": "geometric_rc_ladder",
        "synthesis_type": "incremental_sparse_impulse_fields",
        "correlation_method": "incremental_autocorrelation",
        "generators": [],
    }

    # --------------------------------------------------------
    # Precompute radial grid once
    # --------------------------------------------------------

    radius = frequency_grid(height, width)

    centers, index, counts = radial_bin_data(
        radius,
        args.bins,
    )

    grid_data = (centers, index, counts)

    # --------------------------------------------------------
    # Dashboard initialization
    # --------------------------------------------------------

    STATE["original"] = display_image(original)

    STATE["reconstruction"] = display_image(
        reconstruction
    )

    STATE["residual"] = display_image(
        np.clip(0.5 + residual, 0.0, 1.0)
    )

    STATE["stages"] = args.stages
    STATE["stage"] = 0
    STATE["history"] = []
    STATE["atoms_total"] = 0
    STATE["status"] = "running"

    best_mse = mse(original, reconstruction)

    print(f"Image dimensions: {width} x {height}", flush=True)
    print(f"Candidate families: {len(families)}", flush=True)
    print(f"Initial MSE: {best_mse:.8f}", flush=True)

    print(
        f"Analysis pixels: {width * height:,}",
        flush=True,
    )

    print(
        "Atom matching: incremental autocorrelation",
        flush=True,
    )

    kernel_cache = {}

    total_atoms = 0

    discovery_total = 0.0
    matching_total = 0.0
    synthesis_total = 0.0

    # ========================================================
    # STAGES
    # ========================================================

    for stage in range(args.stages):

        stage_started = time.time()

        update_state(
            stage=stage + 1,
            message=f"Stage {stage + 1}: spectral discovery",
        )

        print(
            f"\nSTAGE {stage + 1}/{args.stages}",
            flush=True,
        )

        # ----------------------------------------------------
        # 1. Spectral family discovery
        # ----------------------------------------------------

        t0 = time.time()

        family, spectral_error, centers, target_power = (
            discover_best_family(
                residual,
                families,
                args.bins,
                grid_data,
            )
        )

        discovery_seconds = time.time() - t0
        discovery_total += discovery_seconds

        if family is None:
            print("No valid family found.", flush=True)
            break

        key = (
            family["rho_num"],
            family["rho_den"],
            family["gamma_num"],
            family["gamma_den"],
            family["n"],
        )

        # ----------------------------------------------------
        # 2. Cached kernel generation
        # ----------------------------------------------------

        if key not in kernel_cache:

            kernel_cache[key] = make_generator(
                family,
                original.shape,
            )

        kernel_fft, kernel = kernel_cache[key]

        print(
            f"  rho={family['rho']:.6f} "
            f"gamma={family['gamma']:.6f} "
            f"n={family['n']} "
            f"alpha={family['alpha']:.5f}",
            flush=True,
        )

        # ----------------------------------------------------
        # 3. Incremental atom matching
        # ----------------------------------------------------

        update_state(
            message=f"Stage {stage + 1}: accelerated atom matching",
        )

        t0 = time.time()

        atoms, contribution = sparse_impulse_fit(
            residual,
            kernel_fft,
            max_atoms=args.atoms_per_stage,
            threshold=args.atom_threshold,
        )

        matching_seconds = time.time() - t0
        matching_total += matching_seconds

        if not atoms:

            print(
                "No useful atoms found; stopping.",
                flush=True,
            )

            break

        # ----------------------------------------------------
        # 4. Whole-image reconstruction
        # ----------------------------------------------------

        t0 = time.time()

        proposed = np.clip(
            reconstruction + contribution,
            0.0,
            1.0,
        )

        proposed_mse = mse(original, proposed)

        synthesis_seconds = time.time() - t0
        synthesis_total += synthesis_seconds

        if proposed_mse >= best_mse:

            print(
                f"Rejected: MSE {proposed_mse:.8f} "
                f"not better than {best_mse:.8f}",
                flush=True,
            )

            break

        reconstruction = proposed

        residual = original - reconstruction

        best_mse = proposed_mse

        total_atoms += len(atoms)

        # ----------------------------------------------------
        # 5. Generator model
        # ----------------------------------------------------

        generator = {
            "family": {
                "rho_num": family["rho_num"],
                "rho_den": family["rho_den"],
                "gamma_num": family["gamma_num"],
                "gamma_den": family["gamma_den"],
                "rho": family["rho"],
                "gamma": family["gamma"],
                "n": family["n"],
                "alpha": family["alpha"],
            },
            "spectral_error": float(spectral_error),
            "atoms": atoms,
        }

        model["generators"].append(generator)

        # ----------------------------------------------------
        # 6. Checkpoint
        # ----------------------------------------------------

        model_bytes = STATE["model_bytes"]

        should_save = (
            (stage + 1) % args.checkpoint_every == 0
            or stage == args.stages - 1
            or args.checkpoint_every == 1
        )

        if should_save:

            model_bytes = save_model(
                model,
                args.output,
                args.compression,
            )

        # ----------------------------------------------------
        # 7. Performance history
        # ----------------------------------------------------

        elapsed_stage = time.time() - stage_started

        row = {
            "stage": stage + 1,
            "rho": family["rho"],
            "gamma": family["gamma"],
            "n": family["n"],
            "alpha": family["alpha"],
            "atoms": len(atoms),
            "mse": best_mse,
            "spectral_error": float(spectral_error),
            "model_bytes": model_bytes,
            "seconds": elapsed_stage,
            "discovery_seconds": discovery_seconds,
            "matching_seconds": matching_seconds,
            "synthesis_seconds": synthesis_seconds,
        }

        STATE["history"].append(row)

        # ----------------------------------------------------
        # 8. Dashboard
        # ----------------------------------------------------

        update_state(
            mse=best_mse,
            model_bytes=model_bytes,
            elapsed=time.time() - started,
            atoms_total=total_atoms,
            discovery_seconds=discovery_total,
            matching_seconds=matching_total,
            synthesis_seconds=synthesis_total,
            reconstruction=display_image(reconstruction),
            residual=display_image(
                np.clip(0.5 + residual * 1.5, 0.0, 1.0)
            ),
            spectrum=display_image(
                normalized_display(
                    np.log1p(np.abs(kernel))
                )
            ),
            message=(
                f"Stage {stage + 1} complete: "
                f"{len(atoms)} atoms"
            ),
        )

        # ----------------------------------------------------
        # 9. Console reporting
        # ----------------------------------------------------

        print(
            f"STAGE {stage + 1}/{args.stages} "
            f"atoms={len(atoms)} "
            f"total_atoms={total_atoms} "
            f"MSE={best_mse:.8f} "
            f"spectral_error={spectral_error:.8g} "
            f"discovery={discovery_seconds:.2f}s "
            f"matching={matching_seconds:.2f}s "
            f"synthesis={synthesis_seconds:.2f}s "
            f"stage_time={elapsed_stage:.2f}s",
            flush=True,
        )

        if should_save:
            print(
                f"  Checkpoint: {model_bytes:,} compressed bytes",
                flush=True,
            )

        # ----------------------------------------------------
        # 10. Snapshots
        # ----------------------------------------------------

        if args.snapshots:

            snapshot = Image.fromarray(
                (
                    np.clip(reconstruction, 0, 1) * 255
                ).astype(np.uint8)
            )

            snapshot.save(
                f"analog_stage_{stage + 1:03d}.png"
            )

            if args.residual_snapshots:

                Image.fromarray(
                    (
                        np.clip(
                            0.5 + residual * 1.5,
                            0,
                            1,
                        ) * 255
                    ).astype(np.uint8)
                ).save(
                    f"analog_residual_{stage + 1:03d}.png"
                )

        if best_mse <= args.target_mse:

            print(
                "Target MSE reached.",
                flush=True,
            )

            break

    # ========================================================
    # FINAL SAVE
    # ========================================================

    final_bytes = save_model(
        model,
        args.output,
        args.compression,
    )

    elapsed = time.time() - started

    update_state(
        model_bytes=final_bytes,
        mse=best_mse,
        elapsed=elapsed,
        atoms_total=total_atoms,
        discovery_seconds=discovery_total,
        matching_seconds=matching_total,
        synthesis_seconds=synthesis_total,
        status="complete",
        message="Synthesis complete",
        reconstruction=display_image(reconstruction),
        residual=display_image(
            np.clip(0.5 + residual * 1.5, 0.0, 1.0)
        ),
    )

    print("\n" + "=" * 70)
    print("ANALOG FRACTAL WORKBENCH 3.0 COMPLETE")
    print("=" * 70)

    print(f"Final MSE:             {best_mse:.9f}")
    print(f"Generators:            {len(model['generators'])}")
    print(f"Total atoms:           {total_atoms:,}")
    print(f"Compressed model:      {final_bytes:,} bytes")
    print(f"Elapsed:               {elapsed:.2f} seconds")
    print(f"Discovery time:        {discovery_total:.2f} seconds")
    print(f"Matching time:         {matching_total:.2f} seconds")
    print(f"Synthesis time:        {synthesis_total:.2f} seconds")
    print(f"Model:                 {args.output}")

    print("=" * 70)


# ============================================================
# ENTRY POINT
# ============================================================

def main():

    parser = argparse.ArgumentParser(
        description=(
            "Analog Fractal Workbench 3.0 "
            "- accelerated whole-image atom discovery"
        )
    )

    parser.add_argument("image")

    parser.add_argument("--stages", type=int, default=16)
    parser.add_argument("--bins", type=int, default=192)

    parser.add_argument(
        "--iterations",
        type=int,
        default=100,
        help="Compatibility option; retained for previous workflows.",
    )

    parser.add_argument(
        "--atoms-per-stage",
        type=int,
        default=256,
    )

    parser.add_argument(
        "--max-candidates",
        type=int,
        default=160,
        help="0 evaluates every candidate family.",
    )

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

    parser.add_argument(
        "--atom-threshold",
        type=float,
        default=0.012,
    )

    parser.add_argument(
        "--target-mse",
        type=float,
        default=0.0005,
    )

    parser.add_argument(
        "--checkpoint-every",
        type=int,
        default=1,
        help="Save model after every N stages.",
    )

    parser.add_argument(
        "--compression",
        type=int,
        default=6,
        help="Zlib compression level, 0 through 9.",
    )

    parser.add_argument(
        "--threads",
        type=int,
        default=0,
        help="Optional BLAS/OpenMP thread limit. 0 leaves defaults unchanged.",
    )

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

    parser.add_argument(
        "--output",
        default="image_fractal_model.json",
    )

    parser.add_argument(
        "--snapshots",
        action="store_true",
    )

    parser.add_argument(
        "--residual-snapshots",
        action="store_true",
    )

    args = parser.parse_args()

    if args.stages < 1:
        parser.error("--stages must be positive")

    if args.bins < 16:
        parser.error("--bins must be at least 16")

    if args.iterations < 1:
        parser.error("--iterations must be positive")

    if args.atoms_per_stage < 1:
        parser.error("--atoms-per-stage must be positive")

    if args.max_candidates < 0:
        parser.error("--max-candidates cannot be negative")

    if args.max_side < 1:
        parser.error("--max-side must be positive")

    if args.checkpoint_every < 1:
        parser.error("--checkpoint-every must be positive")

    if not 0 <= args.compression <= 9:
        parser.error("--compression must be between 0 and 9")

    if args.threads < 0:
        parser.error("--threads cannot be negative")

    # Apply optional numerical library thread limits.
    # These environment variables are most effective when set
    # before NumPy is imported. They are therefore advisory here.
    if args.threads:
        print(
            "NOTE: NumPy was imported before argument parsing. "
            "Thread limits may not affect an already initialized BLAS runtime.",
            flush=True,
        )

    print("=" * 70)
    print("ANALOG FRACTAL WORKBENCH 3.0")
    print("ACCELERATED ATOM DISCOVERY")
    print("=" * 70)

    print(f"Image:             {args.image}")
    print(f"Stages:            {args.stages}")
    print(f"Radial bins:       {args.bins}")
    print(f"Atoms per stage:   {args.atoms_per_stage}")
    print(f"Max candidates:    {args.max_candidates}")
    print(f"Max side:          {args.max_side}")
    print(f"Atom threshold:    {args.atom_threshold}")
    print(f"Checkpoint every:  {args.checkpoint_every}")
    print(f"Compression:       {args.compression}")
    print(f"Output:            {args.output}")

    print("=" * 70)

    server = start_dashboard(args.port)

    print(
        f"Dashboard: http://127.0.0.1:{args.port}",
        flush=True,
    )

    print("Press Ctrl+C to stop.\n", flush=True)

    try:

        run(args)

    except KeyboardInterrupt:

        update_state(
            status="interrupted",
            message="Interrupted by user",
        )

        print("\nInterrupted.", flush=True)

    except Exception as exc:

        update_state(
            status="error",
            message=str(exc),
        )

        raise

    finally:

        server.shutdown()
        server.server_close()


if __name__ == "__main__":
    main()
