
#!/usr/bin/env python3
"""
ANALOG FRACTAL WORKBENCH 3.1
============================

Whole-image reconstruction using:
    - A continuous coarse excitation field
    - Geometric RC ladder frequency responses
    - Oriented and anisotropic spatial kernels
    - Residual-driven translated atom discovery
    - Additive continuous-valued synthesis
    - Exact model serialization and deterministic decoding
    - Live local dashboard

Dependencies:
    py -m pip install numpy pillow

Fit:
    py analog_fractal_workbench.py photograph.jpg
    py analog_fractal_workbench.py photograph.jpg --stages 100
    py analog_fractal_workbench.py photograph.jpg --stages 200 --max-side 512

Decode:
    py analog_fractal_workbench.py --decode image_fractal_model.json

The model stores the coarse excitation samples and every discovered atom.
The decoder rebuilds the same ladder kernels from the saved parameters.

This is a numerical realization of continuous-valued fields, not physical
analog computation. Spatial boundaries are periodic.
"""

from __future__ import annotations

import argparse
import base64
import functools
import io
import json
import math
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

import numpy as np
from PIL import Image


VERSION = "3.1"
MODEL_FORMAT = "ANALOG-FRACTAL-3.1"

STATE = {
    "running": True,
    "stage": 0,
    "total": 0,
    "mse": None,
    "initial_mse": None,
    "model_bytes": 0,
    "atoms": 0,
    "message": "Initializing",
    "images": {},
    "metrics": [],
}

STATE_LOCK = threading.Lock()


# ===========================================================================
# Image input and continuous base field
# ===========================================================================

def load_image(path: str, max_side: int) -> np.ndarray:
    image = Image.open(path).convert("RGB")

    width, height = image.size
    scale = min(1.0, max_side / max(width, height))

    if scale < 1.0:
        new_width = max(8, int(round(width * scale)))
        new_height = max(8, int(round(height * scale)))
        image = image.resize(
            (new_width, new_height),
            Image.Resampling.LANCZOS,
        )

    return np.asarray(image, dtype=np.float32) / 255.0


def resize_rgb(
    array: np.ndarray,
    width: int,
    height: int,
) -> np.ndarray:
    image = Image.fromarray(
        np.rint(np.clip(array, 0.0, 1.0) * 255.0).astype(np.uint8),
        "RGB",
    )
    image = image.resize(
        (width, height),
        Image.Resampling.BICUBIC,
    )
    return np.asarray(image, dtype=np.float32) / 255.0


def make_continuous_base(
    source: np.ndarray,
    base_width: int,
) -> tuple[np.ndarray, np.ndarray]:
    """
    Construct a smooth full-image field from a small set of RGB samples.

    The coarse samples are retained separately because they are the actual
    base-field data required by the decoder.
    """
    height, width, _ = source.shape

    coarse_width = min(base_width, width)
    coarse_height = max(
        4,
        int(round(coarse_width * height / width)),
    )

    small = Image.fromarray(
        np.rint(np.clip(source, 0.0, 1.0) * 255.0).astype(np.uint8),
        "RGB",
    )
    small = small.resize(
        (coarse_width, coarse_height),
        Image.Resampling.LANCZOS,
    )

    coarse = np.asarray(small, dtype=np.float32) / 255.0
    base = resize_rgb(coarse, width, height)

    return coarse, base


# ===========================================================================
# Geometric RC ladder
# ===========================================================================

def derive_phi() -> float:
    """
    Positive fixed point of x^2 = x + 1.

    The value is derived here rather than loaded from a stored lookup table.
    """
    return (1.0 + math.sqrt(5.0)) / 2.0


def candidate_families() -> list[dict]:
    """
    Geometric ladder families.

    Each family describes:
        R_k = rho^k
        C_k = gamma^k

    The quadratic fixed-point family derives its ratio from the fixed-point
    relation. Numerical evaluation uses float64.
    """
    phi = derive_phi()

    return [
        {
            "rho": 1.125,
            "gamma": 1.125,
            "n": 4,
            "label": "near-uniform",
        },
        {
            "rho": 1.25,
            "gamma": 1.25,
            "n": 5,
            "label": "balanced",
        },
        {
            "rho": 1.5,
            "gamma": 1.25,
            "n": 6,
            "label": "asymmetric",
        },
        {
            "rho": phi,
            "gamma": phi,
            "n": 6,
            "label": "quadratic-fixed-point",
        },
    ]


def ladder_impedance(
    omega: np.ndarray,
    rho: float,
    gamma: float,
    stages: int,
) -> np.ndarray:
    """
    Vectorized exact-topology recurrence evaluated numerically:

        Z_k = R_k + 1 / (j*w*C_k + 1/Z_(k+1))

    Final stage:
        Z_(n-1) = R_(n-1) + 1/(j*w*C_(n-1))
    """
    omega = np.asarray(omega, dtype=np.float64)
    omega = np.maximum(omega, 1e-8)

    jw = 1j * omega

    last = stages - 1
    resistance = rho ** last
    capacitance = gamma ** last

    z = resistance + 1.0 / (jw * capacitance)

    for k in range(stages - 2, -1, -1):
        resistance = rho ** k
        capacitance = gamma ** k

        z = resistance + 1.0 / (
            jw * capacitance + 1.0 / z
        )

    return z


def ladder_frequency_response(
    height: int,
    width: int,
    family: dict,
    scale: float,
    aspect: float,
    angle: float,
) -> np.ndarray:
    """
    Construct a two-dimensional anisotropic spatial-frequency response.

    Rotation and aspect ratio alter the frequency radius before it enters
    the geometric RC ladder.

    H(w) = |Z(w) / (Z(w) + R_load)|

    The DC response is subtracted so the spatial kernel has zero mean.
    """
    fy = np.fft.fftfreq(height) * (2.0 * math.pi)
    fx = np.fft.fftfreq(width) * (2.0 * math.pi)

    kx, ky = np.meshgrid(fx, fy)

    c = math.cos(angle)
    s = math.sin(angle)

    u = c * kx + s * ky
    v = -s * kx + c * ky

    radial = np.sqrt(
        (u / aspect) ** 2 +
        (v * aspect) ** 2
    )

    omega = np.maximum(radial * scale, 1e-7)

    z = ladder_impedance(
        omega,
        float(family["rho"]),
        float(family["gamma"]),
        int(family["n"]),
    )

    response = np.abs(z / (z + 1.0))
    response -= response[0, 0]

    return response.astype(np.float64)


@functools.lru_cache(maxsize=256)
def make_kernel_cached(
    height: int,
    width: int,
    rho: float,
    gamma: float,
    stages: int,
    scale: float,
    aspect: float,
    angle: float,
) -> tuple[np.ndarray, np.ndarray]:
    family = {
        "rho": rho,
        "gamma": gamma,
        "n": stages,
    }

    response = ladder_frequency_response(
        height,
        width,
        family,
        scale,
        aspect,
        angle,
    )

    kernel = np.fft.ifft2(response).real
    kernel -= kernel.mean()

    norm = float(np.sqrt(np.sum(kernel * kernel)))

    if norm > 1e-12:
        kernel /= norm
    else:
        kernel.fill(0.0)

    return (
        kernel.astype(np.float32),
        response.astype(np.float32),
    )


def make_kernel(
    height: int,
    width: int,
    family: dict,
    scale: float,
    aspect: float,
    angle: float,
) -> tuple[np.ndarray, np.ndarray]:
    return make_kernel_cached(
        int(height),
        int(width),
        float(family["rho"]),
        float(family["gamma"]),
        int(family["n"]),
        float(scale),
        float(aspect),
        float(angle),
    )


# ===========================================================================
# Candidate ladder bank
# ===========================================================================

def build_candidate_bank(
    height: int,
    width: int,
) -> list[dict]:
    """
    Build a compact bank of distinct ladder responses.

    Four ladder families are crossed with:
        - Two frequency scales
        - Two orientation/anisotropy configurations

    Total: 16 candidates.
    """
    families = candidate_families()

    scales = (0.70, 1.60)

    geometries = (
        (1.0, 0.0),
        (1.8, math.pi / 4.0),
    )

    bank = []

    for family_index, family in enumerate(families):
        for scale in scales:
            for aspect, angle in geometries:
                kernel, response = make_kernel(
                    height,
                    width,
                    family,
                    scale,
                    aspect,
                    angle,
                )

                bank.append({
                    "family_index": family_index,
                    "family": family,
                    "scale": float(scale),
                    "aspect": float(aspect),
                    "angle": float(angle),
                    "kernel": kernel,
                    "kernel_fft": np.fft.fft2(kernel),
                    "response": response,
                })

    return bank


# ===========================================================================
# Residual-driven atom discovery
# ===========================================================================

def correlation_map(
    residual_fft: np.ndarray,
    kernel_fft: np.ndarray,
) -> np.ndarray:
    """
    Circular correlation for all three RGB channels.

    ifft2(FFT(residual) * conj(FFT(kernel))) gives the coefficient field
    for every possible translated kernel position.
    """
    product = (
        residual_fft *
        np.conj(kernel_fft)[:, :, None]
    )

    return np.fft.ifft2(
        product,
        axes=(0, 1),
    ).real


def discover_atom(
    residual: np.ndarray,
    bank: list[dict],
) -> tuple[dict, int, int, np.ndarray, float]:
    """
    Select the translated ladder atom with greatest squared RGB correlation.

    The kernels have unit L2 norm, so the correlation vector is the
    least-squares coefficient vector for that translation.
    """
    residual_fft = np.fft.fft2(
        residual,
        axes=(0, 1),
    )

    best_candidate = None
    best_x = 0
    best_y = 0
    best_coefficients = None
    best_score = -1.0

    for candidate in bank:
        correlations = correlation_map(
            residual_fft,
            candidate["kernel_fft"],
        )

        score_map = np.sum(
            correlations * correlations,
            axis=2,
        )

        flat_index = int(np.argmax(score_map))
        y, x = np.unravel_index(
            flat_index,
            score_map.shape,
        )

        score = float(score_map[y, x])

        if score > best_score:
            best_score = score
            best_candidate = candidate
            best_x = int(x)
            best_y = int(y)
            best_coefficients = correlations[y, x].astype(
                np.float32
            )

    if best_candidate is None:
        raise RuntimeError("No candidate ladder atoms available")

    return (
        best_candidate,
        best_x,
        best_y,
        best_coefficients,
        best_score,
    )


def atom_contribution(
    kernel: np.ndarray,
    x: int,
    y: int,
    coefficients: np.ndarray,
) -> np.ndarray:
    """
    Translate a periodic kernel and apply its RGB coefficient vector.
    """
    shifted = np.roll(
        kernel,
        shift=(y, x),
        axis=(0, 1),
    )

    return (
        shifted[:, :, None] *
        coefficients[None, None, :]
    )


# ===========================================================================
# Model serialization
# ===========================================================================

def create_model(
    width: int,
    height: int,
    coarse: np.ndarray,
    atoms: list[dict],
) -> dict:
    """
    Create the complete decoder input.

    The coarse samples are stored directly as PNG bytes. The decoder
    interpolates them using the same Pillow BICUBIC operation as the encoder.
    """
    coarse_height, coarse_width, _ = coarse.shape

    coarse_image = Image.fromarray(
        np.rint(
            np.clip(coarse, 0.0, 1.0) * 255.0
        ).astype(np.uint8),
        "RGB",
    )

    buffer = io.BytesIO()
    coarse_image.save(
        buffer,
        format="PNG",
        optimize=True,
    )

    families = candidate_families()

    return {
        "format": MODEL_FORMAT,
        "version": VERSION,
        "width": int(width),
        "height": int(height),
        "base_width": int(coarse_width),
        "base_height": int(coarse_height),
        "base_png": base64.b64encode(
            buffer.getvalue()
        ).decode("ascii"),
        "families": families,
        "atoms": atoms,
        "atom_count": len(atoms),
        "boundary": "periodic",
        "kernel_normalization": "unit_l2",
        "coefficient_shrinkage": 0.88,
        "response_definition": "abs(Z/(Z+1))-DC",
    }


def save_model(
    model: dict,
    path: str,
) -> int:
    encoded = json.dumps(
        model,
        separators=(",", ":"),
        ensure_ascii=True,
        allow_nan=False,
    ).encode("utf-8")

    Path(path).write_bytes(encoded)

    size = len(encoded)

    with STATE_LOCK:
        STATE["model_bytes"] = size

    return size


def load_model(path: str) -> dict:
    model = json.loads(
        Path(path).read_text(encoding="utf-8")
    )

    if model.get("format") != MODEL_FORMAT:
        raise ValueError(
            "Unsupported model format. "
            f"Expected {MODEL_FORMAT!r}, got {model.get('format')!r}"
        )

    required = (
        "width",
        "height",
        "base_png",
        "families",
        "atoms",
    )

    for key in required:
        if key not in model:
            raise ValueError(f"Model is missing required field: {key}")

    return model


def decode_model(model_path: str) -> np.ndarray:
    """
    Rebuild the image from the saved coarse field and saved atoms.

    No source photograph is required.
    """
    model = load_model(model_path)

    width = int(model["width"])
    height = int(model["height"])

    coarse_bytes = base64.b64decode(
        model["base_png"],
        validate=True,
    )

    coarse_image = Image.open(
        io.BytesIO(coarse_bytes)
    ).convert("RGB")

    coarse = (
        np.asarray(coarse_image, dtype=np.float32) /
        255.0
    )

    reconstruction = resize_rgb(
        coarse,
        width,
        height,
    )

    families = model["families"]
    atoms = model["atoms"]

    for index, atom in enumerate(atoms):
        family_index = int(atom["family_index"])

        if not 0 <= family_index < len(families):
            raise ValueError(
                f"Invalid family index in atom {index}"
            )

        family = families[family_index]

        kernel, _ = make_kernel(
            height,
            width,
            family,
            float(atom["scale"]),
            float(atom["aspect"]),
            float(atom["angle"]),
        )

        coefficients = np.asarray(
            atom["coefficients"],
            dtype=np.float32,
        )

        if coefficients.shape != (3,):
            raise ValueError(
                f"Invalid RGB coefficients in atom {index}"
            )

        reconstruction += atom_contribution(
            kernel,
            int(atom["x"]),
            int(atom["y"]),
            coefficients,
        )

    return np.clip(
        reconstruction,
        0.0,
        1.0,
    )


# ===========================================================================
# Dashboard image generation
# ===========================================================================

def array_to_png_bytes(array: np.ndarray) -> bytes:
    pixels = np.rint(
        np.clip(array, 0.0, 1.0) * 255.0
    ).astype(np.uint8)

    image = Image.fromarray(pixels, "RGB")

    buffer = io.BytesIO()
    image.save(
        buffer,
        format="PNG",
        optimize=True,
    )

    return buffer.getvalue()


def encode_png(array: np.ndarray) -> str:
    return base64.b64encode(
        array_to_png_bytes(array)
    ).decode("ascii")


def signed_error_image(
    residual: np.ndarray,
) -> np.ndarray:
    """
    Display positive and negative residual separately.

    Red = positive error.
    Blue = negative error.
    Black = near zero.

    This image is an error visualization, not a reconstruction.
    """
    magnitude = np.max(
        np.abs(residual),
        axis=2,
    )

    scale = float(
        np.percentile(magnitude, 99.0)
    )

    if scale < 1e-9:
        scale = 1.0

    normalized = np.clip(
        residual / scale,
        -1.0,
        1.0,
    )

    positive = np.maximum(normalized, 0.0)
    negative = np.maximum(-normalized, 0.0)

    red = np.max(positive, axis=2)
    blue = np.max(negative, axis=2)
    green = 0.10 * np.minimum(red, blue)

    return np.stack(
        [red, green, blue],
        axis=2,
    ).astype(np.float32)


def signed_kernel_image(
    kernel: np.ndarray,
) -> np.ndarray:
    scale = float(
        np.percentile(np.abs(kernel), 99.5)
    )

    if scale < 1e-12:
        scale = 1.0

    value = np.clip(
        kernel / scale,
        -1.0,
        1.0,
    )

    red = np.maximum(value, 0.0)
    blue = np.maximum(-value, 0.0)
    green = 1.0 - np.abs(value)

    return np.stack(
        [red, green, blue],
        axis=2,
    ).astype(np.float32)


def response_image(
    response: np.ndarray,
) -> np.ndarray:
    shifted = np.fft.fftshift(response)
    shifted = np.maximum(shifted, 0.0)

    scale = float(
        np.percentile(shifted, 99.5)
    )

    if scale < 1e-12:
        scale = 1.0

    value = np.clip(
        shifted / scale,
        0.0,
        1.0,
    )

    return np.repeat(
        value[:, :, None],
        3,
        axis=2,
    ).astype(np.float32)


def publish_images(
    source: np.ndarray,
    reconstruction: np.ndarray,
    residual: np.ndarray,
    kernel: np.ndarray,
    response: np.ndarray,
) -> None:
    images = {
        "original": encode_png(source),
        "reconstruction": encode_png(reconstruction),
        "error": encode_png(signed_error_image(residual)),
        "kernel": encode_png(signed_kernel_image(kernel)),
        "response": encode_png(response_image(response)),
    }

    with STATE_LOCK:
        STATE["images"] = images


# ===========================================================================
# Dashboard server
# ===========================================================================

DASHBOARD_HTML = r"""
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Analog Fractal Workbench 3.1</title>
<style>
body {
  margin:20px;
  background:#11151b;
  color:#e5e7eb;
  font-family:system-ui,Arial,sans-serif;
}
h1 {font-size:22px;margin-bottom:4px}
.sub {color:#9ca3af;margin-bottom:18px}
.stats {
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(150px,1fr));
  gap:10px;
  margin-bottom:16px;
}
.stat {background:#202833;padding:12px;border-radius:8px}
.stat b {display:block;font-size:20px;margin-top:5px}
.grid {
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(300px,1fr));
  gap:14px;
}
.panel {background:#202833;padding:10px;border-radius:8px}
.panel h2 {font-size:15px;margin:2px 0 8px}
.panel img {width:100%;height:auto;background:#080b0f}
.note {font-size:12px;color:#aab4c0;margin-top:6px}
#message {color:#cbd5e1;margin:12px 0}
table {width:100%;border-collapse:collapse;font-size:12px}
td,th {
  padding:5px;
  border-bottom:1px solid #374151;
  text-align:left;
}
</style>
</head>
<body>

<h1>Analog Fractal Workbench 3.1</h1>
<div class="sub">
Continuous excitation field · geometric RC ladder · residual-driven atoms
</div>

<div class="stats">
 <div class="stat">Atom<b id="stage">0</b></div>
 <div class="stat">Residual MSE<b id="mse">—</b></div>
 <div class="stat">Serialized model bytes<b id="bytes">0</b></div>
 <div class="stat">Atoms<b id="atoms">0</b></div>
</div>

<div id="message">Waiting for synthesis</div>

<div class="grid">
 <div class="panel">
  <h2>Original</h2>
  <img id="original">
 </div>

 <div class="panel">
  <h2>Reconstruction</h2>
  <img id="reconstruction">
 </div>

 <div class="panel">
  <h2>Signed residual — not a reconstruction</h2>
  <img id="error">
  <div class="note">
  Red and blue indicate opposite error signs. Contrast is amplified.
  </div>
 </div>

 <div class="panel">
  <h2>Latest spatial ladder kernel</h2>
  <img id="kernel">
  <div class="note">
  Red and blue show the signed spatial impulse response.
  </div>
 </div>

 <div class="panel">
  <h2>Latest ladder frequency response</h2>
  <img id="response">
  <div class="note">
  Centered at zero spatial frequency. This is a frequency-domain response.
  </div>
 </div>
</div>

<div class="panel" style="margin-top:14px">
<h2>Recent discoveries</h2>
<table>
<thead>
<tr>
<th>Atom</th>
<th>Family</th>
<th>MSE</th>
<th>Correlation score</th>
</tr>
</thead>
<tbody id="metrics"></tbody>
</table>
</div>

<script>
async function update() {
  try {
    const response = await fetch('/state', {cache:'no-store'});
    const state = await response.json();

    document.getElementById('stage').textContent =
      state.stage + ' / ' + state.total;

    document.getElementById('mse').textContent =
      state.mse === null ? '—' : Number(state.mse).toFixed(7);

    document.getElementById('bytes').textContent =
      Number(state.model_bytes).toLocaleString();

    document.getElementById('atoms').textContent =
      state.atoms;

    document.getElementById('message').textContent =
      state.message;

    for (const key of [
      'original',
      'reconstruction',
      'error',
      'kernel',
      'response'
    ]) {
      if (state.images[key]) {
        document.getElementById(key).src =
          'data:image/png;base64,' + state.images[key];
      }
    }

    const rows = (state.metrics || [])
      .slice(-20)
      .reverse()
      .map(item =>
        '<tr><td>' + item.stage + '</td>' +
        '<td>' + item.family + '</td>' +
        '<td>' + Number(item.mse).toFixed(7) + '</td>' +
        '<td>' + Number(item.score).toFixed(5) + '</td></tr>'
      )
      .join('');

    document.getElementById('metrics').innerHTML = rows;
  } catch (error) {
    document.getElementById('message').textContent =
      'Dashboard connection interrupted';
  }
}

update();
setInterval(update, 1500);
</script>
</body>
</html>
"""


class DashboardHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/":
            data = DASHBOARD_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,
                separators=(",", ":"),
            ).encode("utf-8")

            self.send_response(200)
            self.send_header(
                "Content-Type",
                "application/json",
            )
            self.send_header(
                "Cache-Control",
                "no-store",
            )
            self.send_header(
                "Content-Length",
                str(len(data)),
            )
            self.end_headers()
            self.wfile.write(data)
            return

        self.send_error(404)

    def log_message(self, fmt, *args):
        return


def start_dashboard(port: int) -> ThreadingHTTPServer:
    server = ThreadingHTTPServer(
        ("127.0.0.1", port),
        DashboardHandler,
    )

    thread = threading.Thread(
        target=server.serve_forever,
        daemon=True,
    )
    thread.start()

    return server


# ===========================================================================
# Fitting loop
# ===========================================================================

def fit_atoms(
    source: np.ndarray,
    base: np.ndarray,
    coarse: np.ndarray,
    bank: list[dict],
    stages: int,
    model_path: str,
) -> tuple[np.ndarray, list[dict]]:
    """
    Greedy residual-driven atom synthesis.

    At every stage:
        1. Correlate all ladder kernels against the residual.
        2. Select the best family, scale, orientation, and position.
        3. Apply the RGB coefficient vector.
        4. Update the additive reconstruction and residual.
        5. Periodically serialize the complete decoder model.

    The fitting state is never clipped. Clipping is only applied when
    rendering the final image.
    """
    reconstruction = base.copy()
    residual = source - reconstruction

    initial_mse = float(
        np.mean(residual * residual)
    )

    with STATE_LOCK:
        STATE["stage"] = 0
        STATE["total"] = stages
        STATE["initial_mse"] = initial_mse
        STATE["mse"] = initial_mse
        STATE["atoms"] = 0
        STATE["model_bytes"] = 0
        STATE["metrics"] = []
        STATE["message"] = "Starting atom discovery"

    atoms = []

    last_kernel = bank[0]["kernel"]
    last_response = bank[0]["response"]

    for stage in range(stages):
        (
            candidate,
            x,
            y,
            coefficients,
            score,
        ) = discover_atom(
            residual,
            bank,
        )

        # Shrink the least-squares coefficient slightly to reduce
        # aggressive greedy over-subtraction.
        coefficients = (
            coefficients * 0.88
        ).astype(np.float32)

        contribution = atom_contribution(
            candidate["kernel"],
            x,
            y,
            coefficients,
        )

        reconstruction += contribution
        residual -= contribution

        atom = {
            "family_index": int(candidate["family_index"]),
            "scale": float(candidate["scale"]),
            "aspect": float(candidate["aspect"]),
            "angle": float(candidate["angle"]),
            "x": int(x),
            "y": int(y),
            "coefficients": [
                float(value)
                for value in coefficients
            ],
        }

        atoms.append(atom)

        last_kernel = candidate["kernel"]
        last_response = candidate["response"]

        mse = float(
            np.mean(residual * residual)
        )

        with STATE_LOCK:
            STATE["stage"] = stage + 1
            STATE["atoms"] = len(atoms)
            STATE["mse"] = mse
            STATE["message"] = (
                f"Atom {stage + 1}: "
                f"{candidate['family']['label']}, "
                f"scale={candidate['scale']:.3f}, "
                f"aspect={candidate['aspect']:.2f}, "
                f"angle={candidate['angle']:.3f}"
            )

            STATE["metrics"].append({
                "stage": stage + 1,
                "mse": mse,
                "score": float(score),
                "family": candidate["family"]["label"],
            })

        # Save periodically so interrupted long runs retain progress.
        if (stage + 1) % 8 == 0:
            model = create_model(
                source.shape[1],
                source.shape[0],
                coarse,
                atoms,
            )
            save_model(model, model_path)

        publish_images(
            source,
            reconstruction,
            residual,
            last_kernel,
            last_response,
        )

        print(
            f"ATOM {stage + 1:4d}/{stages} "
            f"family={candidate['family']['label']:<24} "
            f"scale={candidate['scale']:.3f} "
            f"aspect={candidate['aspect']:.2f} "
            f"angle={candidate['angle']:.3f} "
            f"MSE={mse:.8f}"
        )

        # No point continuing once every candidate has negligible
        # correlation with the remaining residual.
        if score < 1e-12:
            print("Stopping: residual correlations are negligible.")
            break

    # Always save the complete final model, including any atoms added
    # after the last periodic checkpoint.
    final_model = create_model(
        source.shape[1],
        source.shape[0],
        coarse,
        atoms,
    )

    model_size = save_model(
        final_model,
        model_path,
    )

    with STATE_LOCK:
        STATE["model_bytes"] = model_size
        STATE["atoms"] = len(atoms)

    return reconstruction, atoms


# ===========================================================================
# Fit workflow
# ===========================================================================

def run_workbench(args) -> None:
    source = load_image(
        args.image,
        args.max_side,
    )

    height, width, _ = source.shape

    print()
    print("ANALOG FRACTAL WORKBENCH 3.1")
    print("============================")
    print(f"Image: {args.image}")
    print(f"Dimensions: {width} x {height}")
    print("Generator: geometric RC ladder")
    print("Excitation: continuous coarse field")
    print("Atom discovery: residual correlation")
    print("Kernel bank: oriented and anisotropic")
    print(f"Atoms requested: {args.stages}")
    print(f"Model: {args.model}")
    print(f"Output: {args.output}")
    print(f"Dashboard: http://127.0.0.1:{args.port}")
    print()

    coarse, base = make_continuous_base(
        source,
        args.base_width,
    )

    initial_residual = source - base
    initial_mse = float(
        np.mean(initial_residual * initial_residual)
    )

    print(
        f"Initial continuous-field MSE: {initial_mse:.8f}"
    )
    print("Building RC ladder candidate bank...")

    bank = build_candidate_bank(
        height,
        width,
    )

    print(f"Candidate kernels: {len(bank)}")
    print("Candidate bank ready.")
    print()

    publish_images(
        source,
        base,
        initial_residual,
        bank[0]["kernel"],
        bank[0]["response"],
    )

    server = start_dashboard(args.port)

    print(
        f"Dashboard available at http://127.0.0.1:{args.port}"
    )
    print()

    try:
        reconstruction, atoms = fit_atoms(
            source,
            base,
            coarse,
            bank,
            args.stages,
            args.model,
        )

        final_residual = source - reconstruction
        final_mse = float(
            np.mean(final_residual * final_residual)
        )

        rendered = np.clip(
            reconstruction,
            0.0,
            1.0,
        )

        Image.fromarray(
            np.rint(rendered * 255.0).astype(np.uint8),
            "RGB",
        ).save(args.output)

        # Decode the saved model and compare it against the in-memory
        # reconstruction. This checks serialization and decoder agreement.
        decoded = decode_model(args.model)

        decoder_error = float(
            np.max(np.abs(decoded - rendered))
        )

        publish_images(
            source,
            reconstruction,
            final_residual,
            bank[-1]["kernel"],
            bank[-1]["response"],
        )

        model_size = Path(args.model).stat().st_size

        with STATE_LOCK:
            STATE["running"] = False
            STATE["stage"] = len(atoms)
            STATE["total"] = args.stages
            STATE["atoms"] = len(atoms)
            STATE["mse"] = final_mse
            STATE["model_bytes"] = model_size
            STATE["message"] = "Synthesis complete; decoder verified"

        print()
        print("SYNTHESIS COMPLETE")
        print("==================")
        print(f"Atoms: {len(atoms)}")
        print(f"Initial MSE: {initial_mse:.8f}")
        print(f"Final MSE:   {final_mse:.8f}")
        print(f"Model bytes: {model_size:,}")
        print(f"Decoder max absolute error: {decoder_error:.10f}")
        print(f"Model: {args.model}")
        print(f"Image: {args.output}")
        print()
        print("Dashboard remains available. Press Ctrl+C to stop.")

        while True:
            time.sleep(1.0)

    except KeyboardInterrupt:
        print("\nStopping dashboard.")

    finally:
        server.shutdown()
        server.server_close()


# ===========================================================================
# Command-line interface
# ===========================================================================

def parse_args():
    parser = argparse.ArgumentParser(
        description=(
            "Whole-image continuous-field fractal synthesis "
            "using geometric RC ladder kernels"
        )
    )

    parser.add_argument(
        "image",
        nargs="?",
        help="Input image",
    )

    parser.add_argument(
        "--decode",
        metavar="MODEL",
        help="Decode a saved model without the source image",
    )

    parser.add_argument(
        "--decoded-output",
        default="decoded.png",
        help="Decoded image output path",
    )

    parser.add_argument(
        "--stages",
        type=int,
        default=32,
        help="Number of atoms to discover",
    )

    parser.add_argument(
        "--iterations",
        type=int,
        default=None,
        help="Alias for --stages",
    )

    parser.add_argument(
        "--base-width",
        type=int,
        default=24,
        help="Width of the continuous coarse excitation field",
    )

    parser.add_argument(
        "--max-side",
        type=int,
        default=512,
        help="Maximum working image dimension",
    )

    parser.add_argument(
        "--port",
        type=int,
        default=8766,
        help="Dashboard port",
    )

    parser.add_argument(
        "--model",
        default="image_fractal_model.json",
        help="Serialized model path",
    )

    parser.add_argument(
        "--output",
        default="analog_fractal_reconstruction.png",
        help="Reconstruction image path",
    )

    return parser.parse_args()


def main():
    args = parse_args()

    if args.decode:
        decoded = decode_model(args.decode)

        Image.fromarray(
            np.rint(decoded * 255.0).astype(np.uint8),
            "RGB",
        ).save(args.decoded_output)

        print(f"Decoded model: {args.decode}")
        print(f"Output image: {args.decoded_output}")
        print(
            f"Dimensions: {decoded.shape[1]} x {decoded.shape[0]}"
        )
        return

    if not args.image:
        raise SystemExit(
            "Provide an input image or use --decode MODEL"
        )

    if args.iterations is not None:
        args.stages = args.iterations

    if args.stages < 1:
        raise SystemExit("--stages must be at least 1")

    if args.base_width < 4:
        raise SystemExit("--base-width must be at least 4")

    if args.max_side < 32:
        raise SystemExit("--max-side must be at least 32")

    if args.port < 1 or args.port > 65535:
        raise SystemExit("--port must be between 1 and 65535")

    if not Path(args.image).is_file():
        raise SystemExit(
            f"Input image does not exist: {args.image}"
        )

    run_workbench(args)


if __name__ == "__main__":
    main()
