#!/usr/bin/env python3
"""
ANALOG FRACTAL WORKBENCH 7.0 — CPU ENSEMBLE
======================================

Stable, bounded-coefficient, multistage spectral image reconstruction.

Workbench 7 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_workbench7.py photograph.jpg

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

More detailed run:
    py analog_fractal_workbench7.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_workbench7.py --decode ^
        analog_fractal_workbench7_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 = "7.0-CPU-ENSEMBLE"
MODEL_FORMAT = "ANALOG-FRACTAL-WORKBENCH"
MODEL_VERSION = 7
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)

    # Use spatial-domain energy directly. rfft2 stores only half the
    # spectrum, so an unweighted sum of |FFT|^2 is NOT Parseval-correct.
    kernel_energy = float(np.sum(kernel.astype(np.float64) ** 2))
    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 7 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": "evidence-weighted whole-image hypothesis ensemble with periodic mutation and global descent guard",
        "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 or model.get("version") != MODEL_VERSION:
        raise ValueError("Unrecognized or unsupported v7 model.")
    width, height = model["analysis_dimensions"]
    reconstruction = np.zeros((height, width, 3), dtype=np.float32)
    total_atoms = 0
    for stage in model["stages"]:
        # v7 stores a population of separately parameterized hypotheses.
        for hypothesis in stage.get("hypotheses", []):
            p = hypothesis["generator"]
            _, kernel_fft, _, _, _ = make_kernel_from_parameters(
                height, width, float(p["rho"]), float(p["gamma"]),
                int(p["depth"]), float(p["center"]), float(p["bandwidth"])
            )
            impulses = np.zeros((height, width, 3), dtype=np.float32)
            for atom in hypothesis.get("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", "effective_hypotheses", "weight_entropy", "prediction_stability",
    ]
    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 7.0 CPU ENSEMBLE | 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 7.0 CPU Ensemble</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 make_hypothesis_generator(height, width, stage, stages, args, index, rng):
    # A deliberately diverse population around the requested RC-ladder seed.
    # Mutations are bounded, deterministic for a given seed, and never alter
    # the user's source image or introduce learned/stored constants.
    rho = float(np.clip(args.rho * math.exp(rng.normal(0.0, 0.16)), 0.35, 3.5))
    gamma = float(np.clip(args.gamma * math.exp(rng.normal(0.0, 0.18)), 0.20, 1.8))
    depth = int(np.clip(args.depth + rng.integers(-2, 3), 1, 24))
    t = stage / max(1, stages - 1)
    base_center = 0.012 * ((0.42 / 0.012) ** t)
    center = float(np.clip(base_center * math.exp(rng.normal(0.0, 0.55)), 0.003, 0.48))
    bandwidth = float(np.clip(0.72 + rng.normal(0.0, 0.13), 0.30, 1.25))
    return make_generator_from_values(height, width, stage, rho, gamma, depth, center, bandwidth)


def make_generator_from_values(height, width, stage, rho, gamma, depth, center, bandwidth):
    kernel, kernel_fft, energy, power, autocorr = make_kernel_from_parameters(
        height, width, rho, gamma, depth, center, bandwidth
    )
    return Generator(stage, rho, gamma, depth, center, bandwidth,
                     kernel, kernel_fft, energy, power, autocorr)


def softmax_logweights(logw, temperature):
    z = np.asarray(logw, dtype=np.float64) / max(float(temperature), 1e-6)
    z -= np.max(z)
    w = np.exp(np.clip(z, -60.0, 0.0))
    total = float(w.sum())
    return w / total if total > 0 and math.isfinite(total) else np.full(len(w), 1.0 / len(w))


def ensemble_stage_fit(residual, stage_index, stages, args, rng):
    """Evidence-weighted population of whole-image kernel hypotheses.

    Every hypothesis proposes an atom against the same current residual.
    Its evidence is updated from its own predictive energy gain. The actual
    committed update is the weight-averaged whole-field proposal, globally
    line-searched against the current residual. This is not winner-take-all.
    """
    started = time.perf_counter()
    h, w, channels = residual.shape
    population = args.population
    generators = [make_hypothesis_generator(h, w, stage_index, stages, args, i, rng)
                  for i in range(population)]
    logw = np.zeros(population, dtype=np.float64)
    hypothesis_atoms = [[] for _ in range(population)]
    archived_hypotheses = []
    evidence_gain = np.zeros(population, dtype=np.float64)
    entropy_sum = ess_sum = stability_sum = 0.0
    previous_prediction = None
    total_rejected = 0
    cycles = max(1, int(math.ceil(args.atoms_per_stage / population)))
    current = residual.copy()
    committed = np.zeros_like(residual)
    accepted = 0
    refresh_count = 0
    stop_reason = "atom budget"

    for cycle in range(cycles):
        if not np.isfinite(current).all():
            stop_reason = "non-finite residual"
            break
        proposals = []
        proposal_gains = np.zeros(population, dtype=np.float64)
        proposal_scores = np.zeros(population, dtype=np.float64)
        for k, gen in enumerate(generators):
            atoms, contribution, fit = batched_atom_fit(
                current, gen, 1, args.atom_threshold, 1,
                args.candidate_multiplier, args.min_distance, args.target_hz,
                args.step_size, args.max_coefficient
            )
            total_rejected += int(fit["rejected_candidates"])
            if atoms and np.isfinite(contribution).all():
                gain = float(np.sum(current.astype(np.float64)**2) -
                             np.sum((current-contribution).astype(np.float64)**2))
                if math.isfinite(gain) and gain > 1e-12:
                    proposals.append((k, atoms[0], contribution))
                    proposal_gains[k] = gain
                    proposal_scores[k] = float(atoms[0].get("score", 0.0))

        if not proposals:
            stop_reason = "population found no positive-gain proposal"
            break
        # Respect the exact stage atom budget when it is not divisible by N.
        proposals = proposals[:max(0, args.atoms_per_stage - accepted)]
        if not proposals:
            stop_reason = "stage atom budget reached"
            break

        # Evidence leak lets a hypothesis recover from a temporary poor fit;
        # gain is log-scaled so a single high-amplitude proposal cannot dominate.
        scale = max(float(np.mean(proposal_gains[proposal_gains > 0])), 1e-9)
        logw = args.leak * logw + np.log1p(proposal_gains / scale) / args.temperature
        weights = softmax_logweights(logw, 1.0)

        # Mixture prediction: every live hypothesis contributes in proportion
        # to current evidence. Missing proposals contribute zero this cycle.
        mixture = np.zeros_like(current)
        for k, atom, contribution in proposals:
            mixture += float(weights[k]) * contribution

        # Exact one-dimensional least-squares line search on the whole field.
        denom = float(np.sum(mixture.astype(np.float64)**2))
        numerator = float(np.sum(current.astype(np.float64)*mixture.astype(np.float64)))
        alpha = numerator / denom if denom > 1e-20 else 0.0
        alpha = float(np.clip(alpha, 0.0, 1.0))
        if not math.isfinite(alpha) or alpha <= 1e-9:
            stop_reason = "mixture direction had no positive descent"
            break
        update = (alpha * mixture).astype(np.float32)
        next_residual = current - update
        old_energy = float(np.sum(current.astype(np.float64)**2))
        new_energy = float(np.sum(next_residual.astype(np.float64)**2))
        if not np.isfinite(next_residual).all() or new_energy >= old_energy - 1e-12:
            stop_reason = "mixture rejected by global energy guard"
            break

        # Store exact per-hypothesis atom coefficients after mixture scaling.
        # Each candidate's own contribution is weighted; the common alpha is
        # also applied so the JSON decoder reproduces the committed field.
        for k, atom, contribution in proposals:
            scaled = np.asarray(atom["rgb"], dtype=np.float64) * (alpha * weights[k])
            stored = dict(atom)
            stored["rgb"] = [float(v) for v in scaled]
            hypothesis_atoms[k].append(stored)
            evidence_gain[k] += proposal_gains[k] * float(weights[k])
        current = next_residual.astype(np.float32, copy=False)
        committed += update
        accepted += len(proposals)

        # Diagnostics for the population's weight distribution and predicted
        # whole-field texture. ESS and entropy expose collapse/diversity.
        ess_sum += 1.0 / max(float(np.sum(weights**2)), 1e-12)
        entropy_sum += -float(np.sum(weights * np.log(weights + 1e-300)))
        prediction = mixture
        if previous_prediction is not None:
            stability_sum += float(np.mean(np.abs(
                np.log(np.abs(prediction)+1e-8)-np.log(np.abs(previous_prediction)+1e-8)
            )))
        previous_prediction = prediction.copy()

        # Periodic population refresh: replace the weakest tenth with bounded
        # mutations of strong hypotheses, preserving evidence-weighted search.
        if args.refresh > 0 and (cycle + 1) % args.refresh == 0 and population >= 4:
            order = np.argsort(logw)
            count = max(1, population // 10)
            top = order[::-1][:max(1, population // 5)]
            median = float(np.median(logw))
            for slot in order[:count]:
                parent = int(top[int(rng.integers(0, len(top)))])
                old = generators[parent]
                if hypothesis_atoms[int(slot)]:
                    archived_hypotheses.append({
                        "generator": generator_record(generators[int(slot)]),
                        "atoms": hypothesis_atoms[int(slot)],
                        "weight_evidence": float(evidence_gain[int(slot)]),
                    })
                rho = float(np.clip(old.rho * math.exp(rng.normal(0, 0.12)), 0.35, 3.5))
                gamma = float(np.clip(old.gamma * math.exp(rng.normal(0, 0.14)), 0.20, 1.8))
                depth = int(np.clip(old.depth + rng.integers(-1, 2), 1, 24))
                center = float(np.clip(old.center * math.exp(rng.normal(0, 0.35)), 0.003, 0.48))
                bandwidth = float(np.clip(old.bandwidth + rng.normal(0, 0.08), 0.30, 1.25))
                generators[int(slot)] = make_generator_from_values(
                    h, w, stage_index, rho, gamma, depth, center, bandwidth
                )
                logw[int(slot)] = median
                hypothesis_atoms[int(slot)] = []
                evidence_gain[int(slot)] = 0.0
            refresh_count += count

        if accepted >= args.atoms_per_stage:
            break

    # Discard hypotheses with no stored atoms; preserve exact synthesis.
    records = list(archived_hypotheses)
    for k, atoms in enumerate(hypothesis_atoms):
        if atoms:
            records.append({
                "generator": generator_record(generators[k]),
                "atoms": atoms,
                "weight_evidence": float(evidence_gain[k]),
            })
    elapsed = max(time.perf_counter()-started, 1e-9)
    atom_count = sum(len(x["atoms"]) for x in records)
    weights = softmax_logweights(logw, 1.0)
    entropy = -float(np.sum(weights*np.log(weights+1e-300)))
    ess = 1.0/max(float(np.sum(weights**2)), 1e-12)
    metrics = {
        "backend":"CPU ensemble", "fft_backend":fft_backend_name(),
        "workers":FFT_WORKERS if SCIPY_FFT_AVAILABLE else 1,
        "atoms":atom_count, "hypotheses":population, "cycles":cycle+1 if 'cycle' in locals() else 0,
        "batches":cycle+1 if 'cycle' in locals() else 0,
        "rejected_candidates":total_rejected, "seconds":elapsed,
        "atoms_per_second":atom_count/elapsed, "target_hz":int(args.target_hz),
        "target_met":bool(atom_count/elapsed >= args.target_hz),
        "predicted_energy_gain":float(np.sum(residual.astype(np.float64)**2)-np.sum(current.astype(np.float64)**2)),
        "stop_reason":stop_reason, "effective_hypotheses":ess,
        "weight_entropy":entropy, "mean_effective_hypotheses":ess_sum/max(1, cycle+1 if 'cycle' in locals() else 1),
        "mean_weight_entropy":entropy_sum/max(1, cycle+1 if 'cycle' in locals() else 1),
        "prediction_stability":stability_sum/max(1, (cycle if 'cycle' in locals() else 0)),
        "population_refreshes":refresh_count, "leak":args.leak,
        "temperature":args.temperature,
    }
    return records, committed, metrics, current


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)
    rng = np.random.default_rng(args.seed)
    print("="*76)
    print("ANALOG FRACTAL WORKBENCH 7.0 — EVIDENCE-WEIGHTED CPU ENSEMBLE")
    print("="*76)
    print(f"Input:          {input_path}\nOutput:         {output_dir}")
    print(f"FFT backend:    {fft_backend_name()} | workers: {FFT_WORKERS if SCIPY_FFT_AVAILABLE else 1}")
    print(f"Population:     {args.population} whole-image hypotheses")
    print(f"Leak/temp:      {args.leak:.4f} / {args.temperature:.4f}")
    print(f"Refresh:        every {args.refresh} cycles")
    print("CUDA:           disabled")
    source, original_size, analysis_size = load_rgb(input_path, args.max_side)
    height, width, _ = source.shape
    print(f"Original:       {original_size[0]} x {original_size[1]}\nWorking:        {width} x {height}")
    print(f"Stages:         {args.stages} | atom budget/stage: {args.atoms_per_stage}")
    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=[]; stage_records=[]; metric_rows=[]; 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("\n"+"-"*76+f"\nSTAGE {stage_number:03d}/{args.stages:03d}\n"+"-"*76)
            before_rms,before_max=finite_stats(residual)
            energy_before=float(np.sum(residual.astype(np.float64)**2))
            hypotheses, contribution, fit, proposed_residual = ensemble_stage_fit(
                residual,stage_index,args.stages,args,rng)
            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")
            accepted_stage=finite_stage and energy_after < energy_before-1e-12
            atoms=[]
            if accepted_stage:
                residual=candidate_residual.astype(np.float32,copy=False)
                reconstruction+=contribution
                for hi,hyp in enumerate(hypotheses):
                    for atom in hyp["atoms"]:
                        item=dict(atom); item["stage"]=stage_index; item["hypothesis"]=hi
                        atoms.append(item)
                all_atoms.extend(atoms); total_atoms+=len(atoms)
                stage_records.append({"hypotheses":hypotheses,"metrics":fit})
            else:
                completed_normally=False
                stop_message="stage rollback: ensemble mixture failed global residual descent"
                fit["stop_reason"]=stop_message
            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":accepted_stage,
                 "stop_reason":fit["stop_reason"],"effective_hypotheses":fit["effective_hypotheses"],
                 "weight_entropy":fit["weight_entropy"],"prediction_stability":fit["prediction_stability"]}
            metric_rows.append(row)
            print(f"Hypotheses:     {fit['hypotheses']} | effective: {fit['effective_hypotheses']:.2f}")
            print(f"Atoms:          {len(atoms):,} | cycles: {fit['cycles']}")
            print(f"Weight entropy: {fit['weight_entropy']:.4f} | stability: {fit['prediction_stability']:.5f}")
            print(f"Fit time:       {fit['seconds']:.2f}s | rate: {fit['atoms_per_second']:.1f} atoms/s")
            print(f"Residual RMS:   {before_rms:.6f} -> {after_rms:.6f}")
            print(f"Stage accepted: {'YES' if accepted_stage else 'NO — ROLLED BACK'}")
            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
            status={"version":VERSION,"state":"running" if accepted_stage 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":total_atoms/max(elapsed,1e-9),
                    "population":args.population,"effective_hypotheses":fit["effective_hypotheses"],
                    "weight_entropy":fit["weight_entropy"],"prediction_stability":fit["prediction_stability"],
                    "residual_rms":after_rms,"residual_max":after_max,
                    "stage_accepted":accepted_stage,"stop_reason":fit["stop_reason"],"elapsed_seconds":elapsed}
            write_json(output_dir/"status.json",status)
            if accepted_stage 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 accepted_stage: break
            if args.stop_rms>0 and after_rms<=args.stop_rms:
                stop_message=f"early stop: residual RMS <= {args.stop_rms}"; break
    except KeyboardInterrupt:
        completed_normally=False; stop_message="interrupted by user"
        print("\nInterrupted. Saving last committed ensemble model.")

    total_elapsed=time.perf_counter()-total_started
    overall_rate=total_atoms/max(total_elapsed,1e-9)
    final_rms,final_max=finite_stats(source-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))
    files=["source.png","reconstruction.png","residual.png","fractal_map.png",
           "reconstruction_progress.gif","metrics.csv","image_fractal_model.json"]
    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,"population":args.population,
                  "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":files}
    write_json(output_dir/"status.json",final_status)
    print("\n"+"="*76+"\nWORKBENCH 7.0 COMPLETE\n"+"="*76)
    print(f"Stages committed: {len(stage_records)} | atoms: {total_atoms:,}")
    print(f"Elapsed: {total_elapsed:.2f}s | rate: {overall_rate:.1f} atoms/s")
    print(f"Final residual: RMS {final_rms:.6f} | max {final_max:.6f}")
    print(f"State: {final_status['state']} | {stop_message}")
    print(f"Output directory: {output_dir}")
    for name in files:
        p=output_dir/name
        if p.exists(): print(f"  {name:36s} {p.stat().st_size/1024:9.1f} KB")
    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 7.0 — CPU evidence-weighted ensemble",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

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

    parser.add_argument("--stages", type=int, default=8)
    parser.add_argument("--atoms-per-stage", type=int, default=64)
    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("--population", type=int, default=8, help="Concurrent whole-image hypotheses")
    parser.add_argument("--temperature", type=float, default=1.0, help="Evidence temperature; higher preserves diversity")
    parser.add_argument("--leak", type=float, default=0.98, help="Evidence persistence per cycle, 0..1")
    parser.add_argument("--refresh", type=int, default=5, help="Refresh weakest hypotheses every N cycles; 0 disables")
    parser.add_argument("--seed", type=int, default=7)

    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.population < 2:
        raise ValueError("--population must be at least 2.")
    if args.temperature <= 0:
        raise ValueError("--temperature must be positive.")
    if not (0.0 <= args.leak <= 1.0):
        raise ValueError("--leak must be between 0 and 1.")
    if args.refresh < 0:
        raise ValueError("--refresh cannot be negative.")
    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())
