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

Discover continuous spatial-spectrum generators using the
geometric RC ladder.

Uses:
    R[k] = R0 * rho**k
    C[k] = C0 * gamma**k

    Z[k] = R[k] + 1/(s*C[k] + 1/Z[k+1])

The image is analyzed as a complete 2D spatial field.

Search:
    1. Calculate the image's radial spatial power spectrum.
    2. Generate candidate RC ladder responses.
    3. Select the best response against the spectral residual.
    4. Jointly refit all selected responses.
    5. Repeat.
    6. Reconstruct using the original Fourier phase.
    7. Display the spatial residual and spectral fit.

The original image_structures.sqlite3 is never modified.

Outputs:
    image_fractal_model.json

Dashboard:
    http://127.0.0.1:8766

Run:
    py analog_fractal_workbench.py photograph.jpg

Options:
    --stages 16
    --bins 192
    --iterations 100
"""

import argparse
import io
import json
import math
import os
import threading
import time
import hashlib

from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse

import numpy as np
from PIL import Image, ImageOps


HOST = "127.0.0.1"
PORT = 8766

PHI = (1.0 + math.sqrt(5.0)) / 2.0

LOCK = threading.RLock()

STATE = {
    "status": "Starting",
    "stage": 0,
    "stages": 0,
    "mse": None,
    "spectral_error": None,
    "model_bytes": 0,
    "bpp_model": None,
    "height": 0,
    "width": 0,
    "selected": [],
    "spectrum": [],
    "events": [],
    "revision": 0,
    "seed_vocabulary": 0,
}

SOURCE = None
RECONSTRUCTION = None
RESIDUAL = None

IMAGE_CACHE = {}


# ============================================================
# Original seed vocabulary: read-only
# ============================================================

def seed_count(path):
    if not os.path.exists(path):
        return 0

    import sqlite3

    db = sqlite3.connect(path)

    try:
        exists = db.execute("""
            SELECT COUNT(*) FROM sqlite_master
            WHERE type='table' AND name='structures'
        """).fetchone()[0]

        if not exists:
            return 0

        return db.execute(
            "SELECT COUNT(*) FROM structures"
        ).fetchone()[0]

    finally:
        db.close()


# ============================================================
# Geometric RC ladder
# ============================================================

def ladder_impedance(omega, rho, gamma, n, tau):
    """
    Exact topology of the user's geometric RC ladder,
    evaluated numerically over an array of angular frequencies.

    R0 = 1
    C0 = tau

    Therefore R0*C0 = tau.

    Overall impedance scale is irrelevant to normalized
    spectral-shape comparison.
    """
    k = np.arange(n, dtype=np.float64)

    R = rho ** k
    C = tau * (gamma ** k)

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

    Y = s * C[-1]
    Z = R[-1] + 1.0 / np.where(
        np.abs(Y) > 1e-30, Y, 1e-30
    )

    for j in range(n - 2, -1, -1):
        Y = s * C[j] + 1.0 / Z
        Z = R[j] + 1.0 / Y

    return Z


def ladder_power_response(freq, rho, gamma, n, tau):
    """
    Candidate spatial power-spectrum envelope.

    The RC ladder impedance magnitude squared supplies
    the scale-dependent response.
    """
    omega = 2.0 * np.pi * np.maximum(freq, 1e-10)

    Z = ladder_impedance(
        omega, rho, gamma, n, tau
    )

    power = np.abs(Z) ** 2

    power = np.nan_to_num(
        power,
        nan=0.0,
        posinf=0.0,
        neginf=0.0
    )

    power = np.maximum(power, 0.0)

    total = power.sum()

    if total <= 1e-30:
        return None

    return power / total


# ============================================================
# Candidate family
# ============================================================

def candidate_parameters():
    ratios = [
        (1.25, 1.25),
        (1.5, 1.5),
        (2.0, 2.0),
        (3.0, 3.0),
        (2.0, 1.5),
        (1.5, 2.0),
        (3.0, 2.0),
        (2.0, 3.0),
        (PHI, PHI),
        (PHI, PHI ** 2),
        (PHI ** 2, PHI),
    ]

    depths = [4, 8, 12, 16, 24]

    scales = [
        0.1, 0.3, 1.0, 3.0,
        10.0, 30.0, 100.0,
        300.0, 1000.0, 3000.0
    ]

    result = []

    for rho, gamma in ratios:
        for n in depths:
            for tau in scales:
                result.append({
                    "rho": float(rho),
                    "gamma": float(gamma),
                    "n": int(n),
                    "tau": float(tau),
                })

    return result


# ============================================================
# Whole-image spatial spectrum
# ============================================================

def radial_geometry(height, width, bins):
    fy = np.fft.fftfreq(height)
    fx = np.fft.fftfreq(width)

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

    radius = np.sqrt(xx * xx + yy * yy)

    max_radius = math.sqrt(0.5)

    index = np.floor(
        radius / max_radius * bins
    ).astype(np.int32)

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

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

    centers = (
        (np.arange(bins) + 0.5)
        / bins
        * max_radius
    )

    return index, counts, centers


def radial_profile(power, index, counts):
    sums = np.bincount(
        index.ravel(),
        weights=power.ravel(),
        minlength=len(counts)
    )

    profile = sums / np.maximum(counts, 1.0)

    # Fill any empty radial bins by interpolation.
    valid = counts > 0

    if not np.all(valid):
        profile = np.interp(
            np.arange(len(profile)),
            np.flatnonzero(valid),
            profile[valid]
        )

    return np.maximum(profile, 0.0)


def image_spectra(image, bins):
    """
    FFT of all three channels.

    Returns:
        Fourier coefficients
        normalized radial power profiles
        total channel powers
        radial index map
        radial bin centers
    """
    h, w, _ = image.shape

    index, counts, centers = radial_geometry(
        h, w, bins
    )

    fourier = np.fft.fft2(
        image.astype(np.float64),
        axes=(0, 1)
    )

    profiles = []
    totals = []

    for channel in range(3):
        power = np.abs(fourier[..., channel]) ** 2

        profile = radial_profile(
            power, index, counts
        )

        total = float(profile.sum())

        if total <= 1e-30:
            total = 1.0

        profiles.append(profile / total)
        totals.append(total)

    return (
        fourier,
        np.asarray(profiles),
        np.asarray(totals),
        index,
        centers
    )


# ============================================================
# Candidate dictionary
# ============================================================

def build_dictionary(parameters, centers):
    matrix = []

    valid_parameters = []

    for p in parameters:

        response = ladder_power_response(
            centers,
            p["rho"],
            p["gamma"],
            p["n"],
            p["tau"]
        )

        if response is None:
            continue

        matrix.append(response)
        valid_parameters.append(p)

    return (
        np.asarray(matrix, dtype=np.float64).T,
        valid_parameters
    )


# ============================================================
# Joint nonnegative coefficient fitting
# ============================================================

def fit_joint(B, target, iterations=100, penalty=1e-7):
    """
    Jointly refit every selected generator against the
    complete target spectrum.

    Nonnegative coordinate descent.

    B:      bins x selected generators
    target: bins x color channels

    Returns:
        coefficients: generators x channels
        residual:      bins x channels
    """
    if B.shape[1] == 0:
        return (
            np.zeros((0, target.shape[1])),
            target.copy()
        )

    gram = B.T @ B
    correlation = B.T @ target

    count = B.shape[1]
    channels = target.shape[1]

    coefficients = np.zeros(
        (count, channels),
        dtype=np.float64
    )

    norms = np.maximum(
        np.diag(gram),
        1e-20
    )

    for _ in range(iterations):

        for j in range(count):

            other = (
                gram[j] @ coefficients
                - gram[j, j] * coefficients[j]
            )

            new_value = (
                correlation[j] - other - penalty
            ) / norms[j]

            new_value = np.maximum(new_value, 0.0)

            coefficients[j] = new_value

    residual = target - B @ coefficients

    return coefficients, residual


def candidate_score(B, residual, selected_indices):
    """
    Score unselected candidates by their joint ability to
    explain remaining positive spectral energy.
    """
    if not selected_indices:
        available = np.arange(B.shape[1])
    else:
        mask = np.ones(B.shape[1], dtype=bool)
        mask[selected_indices] = False
        available = np.flatnonzero(mask)

    if len(available) == 0:
        return None, 0.0

    candidates = B[:, available]

    correlation = candidates.T @ residual
    correlation = np.maximum(correlation, 0.0)

    norms = np.maximum(
        np.sum(candidates * candidates, axis=0),
        1e-20
    )

    scores = np.sum(
        correlation * correlation,
        axis=1
    ) / norms

    best_position = int(np.argmax(scores))

    return (
        int(available[best_position]),
        float(scores[best_position])
    )


# ============================================================
# Reconstruction using original phase
# ============================================================

def reconstruct_image(
    original_fourier,
    coefficients,
    B_selected,
    totals,
    index,
    height,
    width
):
    """
    Reconstruct spectral amplitudes from the selected
    ladder power envelopes.

    Retains original Fourier phase.

    This is a spectral reconstruction experiment, not
    yet a self-contained compressed image decoder: the
    original phase has not been encoded into the model.
    """
    if B_selected.shape[1]:
        profiles = B_selected @ coefficients
    else:
        profiles = np.zeros(
            (B_selected.shape[0], 3)
        )

    output_fourier = np.zeros_like(
        original_fourier,
        dtype=np.complex128
    )

    for channel in range(3):

        profile = np.maximum(
            profiles[:, channel],
            0.0
        )

        total = profile.sum()

        if total > 1e-30:
            profile /= total

        power_map = (
            profile[index] * totals[channel]
        )

        amplitude = np.sqrt(
            np.maximum(power_map, 0.0)
        )

        original = original_fourier[..., channel]

        original_amplitude = np.abs(original)

        phase = np.zeros_like(
            original,
            dtype=np.complex128
        )

        nonzero = original_amplitude > 1e-20

        phase[nonzero] = (
            original[nonzero]
            / original_amplitude[nonzero]
        )

        output_fourier[..., channel] = (
            phase * amplitude
        )

        # Preserve the exact DC component.
        output_fourier[0, 0, channel] = (
            original_fourier[0, 0, channel]
        )

    reconstructed = np.fft.ifft2(
        output_fourier,
        axes=(0, 1)
    ).real

    return np.clip(
        reconstructed, 0, 255
    ).astype(np.uint8), profiles


# ============================================================
# Visualizations
# ============================================================

def residual_image(original, reconstructed):
    delta = (
        original.astype(np.float64)
        - reconstructed.astype(np.float64)
    )

    magnitude = np.abs(delta)

    scale = max(
        float(np.percentile(magnitude, 99)),
        1.0
    )

    normalized = np.clip(
        magnitude / scale,
        0,
        1
    )

    result = np.zeros_like(
        original,
        dtype=np.float64
    )

    signed = delta.mean(axis=2)

    result[..., 0] = (
        normalized.mean(axis=2) * 255
        * (signed > 0)
    )

    result[..., 2] = (
        normalized.mean(axis=2) * 255
        * (signed < 0)
    )

    result[..., 1] = (
        normalized.mean(axis=2) * 24
    )

    return np.clip(
        result, 0, 255
    ).astype(np.uint8)


def update_images():
    global IMAGE_CACHE

    with LOCK:
        arrays = {
            "original": SOURCE,
            "reconstruction": RECONSTRUCTION,
            "residual": RESIDUAL,
        }

        for name, array in arrays.items():
            if array is None:
                continue

            output = io.BytesIO()

            Image.fromarray(
                np.asarray(array, dtype=np.uint8)
            ).save(
                output,
                format="JPEG",
                quality=90
            )

            IMAGE_CACHE[name] = output.getvalue()


# ============================================================
# Model serialization and real model size
# ============================================================

def make_model(selected, coefficients, parameters,
               image_shape, bins, seed_vocabulary):

    generators = []

    for j, candidate_index in enumerate(selected):

        p = parameters[candidate_index]

        generators.append({
            "rho": p["rho"],
            "gamma": p["gamma"],
            "n": p["n"],
            "tau": p["tau"],
            "channel_coefficients": [
                float(v) for v in coefficients[j]
            ],
        })

    return {
        "format": "ANALOG-RC-SPATIAL-FRACTAL-1",
        "image_width": int(image_shape[1]),
        "image_height": int(image_shape[0]),
        "channels": 3,
        "radial_bins": int(bins),
        "seed_vocabulary": int(seed_vocabulary),
        "generator_count": len(generators),
        "generators": generators,
        "decoder": {
            "method": "radial_power_envelope_with_source_phase",
            "phase_embedded": False,
        },
    }


def save_model(path, model):
    raw = json.dumps(
        model,
        separators=(",", ":"),
        sort_keys=True
    ).encode("utf-8")

    with open(path, "wb") as f:
        f.write(raw)

    return len(raw)


# ============================================================
# Discovery engine
# ============================================================

def run_engine(
    image_path,
    seed_db,
    stages,
    bins,
    iterations,
    model_path
):
    global SOURCE, RECONSTRUCTION, RESIDUAL

    try:
        image = Image.open(image_path)
        image = ImageOps.exif_transpose(image).convert("RGB")

        SOURCE = np.asarray(image, dtype=np.uint8)

        height, width = SOURCE.shape[:2]

        vocabulary = seed_count(seed_db)

        with LOCK:
            STATE["seed_vocabulary"] = vocabulary
            STATE["height"] = height
            STATE["width"] = width
            STATE["stages"] = stages
            STATE["status"] = "Analyzing complete image"

        (
            original_fourier,
            target,
            totals,
            radial_index,
            centers
        ) = image_spectra(SOURCE, bins)

        parameters = candidate_parameters()

        with LOCK:
            STATE["status"] = (
                f"Generating {len(parameters)} analog candidates"
            )

        B_all, parameters = build_dictionary(
            parameters,
            centers
        )

        selected = []
        coefficients = np.zeros((0, 3))
        B_selected = np.zeros((bins, 0))
        current_reconstruction = np.full_like(
            SOURCE, 127
        )

        for stage in range(stages):

            with LOCK:
                STATE["stage"] = stage + 1
                STATE["status"] = (
                    f"Searching analog generators: "
                    f"{stage + 1}/{stages}"
                )

            # Current global fit and spectral residual.
            coefficients, spectral_residual = fit_joint(
                B_selected,
                target.T,
                iterations=iterations
            )

            candidate, score = candidate_score(
                B_all,
                spectral_residual,
                selected
            )

            if candidate is None or score <= 1e-18:
                with LOCK:
                    STATE["status"] = (
                        "No further useful generator found"
                    )
                break

            selected.append(candidate)

            B_selected = B_all[:, selected]

            # Jointly refit every selected generator.
            coefficients, spectral_residual = fit_joint(
                B_selected,
                target.T,
                iterations=iterations
            )

            # Remove generators whose contribution is negligible,
            # then jointly refit the surviving collection.
            keep = [
                j for j in range(len(selected))
                if float(np.max(coefficients[j])) > 1e-8
            ]

            if len(keep) < len(selected):
                selected = [selected[j] for j in keep]
                B_selected = B_all[:, selected]

                coefficients, spectral_residual = fit_joint(
                    B_selected,
                    target.T,
                    iterations=iterations
                )

            current_reconstruction, profiles = reconstruct_image(
                original_fourier,
                coefficients,
                B_selected,
                totals,
                radial_index,
                height,
                width
            )

            delta = (
                SOURCE.astype(np.float64)
                - current_reconstruction.astype(np.float64)
            )

            mse = float(np.mean(delta ** 2))

            spectral_error = float(
                np.mean(spectral_residual ** 2)
            )

            model = make_model(
                selected,
                coefficients,
                parameters,
                SOURCE.shape,
                bins,
                vocabulary
            )

            model_bytes = save_model(
                model_path,
                model
            )

            bpp = model_bytes * 8 / (
                height * width
            )

            current_residual = residual_image(
                SOURCE,
                current_reconstruction
            )

            with LOCK:
                RECONSTRUCTION = current_reconstruction
                RESIDUAL = current_residual

                STATE["mse"] = round(mse, 5)
                STATE["spectral_error"] = round(
                    spectral_error, 10
                )
                STATE["model_bytes"] = model_bytes
                STATE["bpp_model"] = round(bpp, 6)
                STATE["revision"] += 1

                STATE["selected"] = [
                    {
                        "rho": parameters[i]["rho"],
                        "gamma": parameters[i]["gamma"],
                        "n": parameters[i]["n"],
                        "tau": parameters[i]["tau"],
                        "coefficients": [
                            round(float(v), 7)
                            for v in coefficients[j]
                        ],
                    }
                    for j, i in enumerate(selected)
                ]

                STATE["spectrum"] = [
                    {
                        "frequency": float(centers[i]),
                        "target": [
                            float(v) for v in target[:, i]
                        ],
                        "fitted": [
                            float(v) for v in profiles[i]
                        ],
                    }
                    for i in range(bins)
                ]

                STATE["events"].append({
                    "stage": stage + 1,
                    "rho": parameters[candidate]["rho"],
                    "gamma": parameters[candidate]["gamma"],
                    "n": parameters[candidate]["n"],
                    "tau": parameters[candidate]["tau"],
                    "score": score,
                    "mse": mse,
                    "model_bytes": model_bytes,
                })

                STATE["events"] = STATE["events"][-100:]

                STATE["status"] = (
                    f"Stage {stage + 1} complete"
                )

            update_images()

            print(
                f"STAGE {stage + 1}/{stages} "
                f"rho={parameters[candidate]['rho']:.6f} "
                f"gamma={parameters[candidate]['gamma']:.6f} "
                f"n={parameters[candidate]['n']} "
                f"tau={parameters[candidate]['tau']:.3f} "
                f"MSE={mse:.4f} "
                f"spectral_error={spectral_error:.9f} "
                f"model_bytes={model_bytes}"
            )

        with LOCK:
            STATE["status"] = "Complete"

    except Exception as exc:
        with LOCK:
            STATE["status"] = "ERROR: " + str(exc)

        raise


# ============================================================
# Live dashboard
# ============================================================

HTML = r"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Analog Fractal Workbench</title>
<style>
* {box-sizing:border-box}
body {
    margin:0;padding:18px;
    background:#10141b;color:#e8edf5;
    font-family:Segoe UI,Arial,sans-serif;
}
h2 {margin:0 0 12px}
h3 {margin:4px 0 10px}
small {color:#9baabd}
.stats {
    display:grid;
    grid-template-columns:repeat(5,minmax(100px,1fr));
    gap:9px;margin-bottom:12px;
}
.stat {
    background:#202a36;border:1px solid #354456;
    border-radius:8px;padding:10px;text-align:center;
}
.stat strong {
    display:block;font-size:21px;
    overflow-wrap:anywhere;
}
.stat span {font-size:11px;color:#9baabd}
.grid {
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
    gap:12px;
}
.panel {
    min-width:0;background:#1a222d;
    border:1px solid #354456;border-radius:9px;
    padding:12px;
}
img {width:100%;display:block;border-radius:5px}
canvas {width:100%;display:block}
#events {
    max-height:230px;overflow:auto;
    font:12px Consolas,monospace;color:#bdcce0;
}
#generators {
    max-height:260px;overflow:auto;
    font:12px Consolas,monospace;
}
@media(max-width:850px) {
    .grid {grid-template-columns:1fr}
    .stats {grid-template-columns:repeat(2,1fr)}
}
</style>
</head>
<body>

<h2>ANALOG FRACTAL DISCOVERY</h2>

<div class="stats">
 <div class="stat"><strong id="stage">0</strong><span>Search stage</span></div>
 <div class="stat"><strong id="mse">—</strong><span>Image MSE</span></div>
 <div class="stat"><strong id="spectral">—</strong><span>Spectral error</span></div>
 <div class="stat"><strong id="bytes">0</strong><span>Model bytes</span></div>
 <div class="stat"><strong id="bpp">—</strong><span>Model bits / pixel</span></div>
</div>

<div class="panel">
 <div id="status">Starting...</div>
 <small id="dimensions"></small>
</div>

<br>

<div class="grid">
 <div class="panel">
  <h3>1. Original image</h3>
  <img src="/view/original" alt="Original image">
 </div>

 <div class="panel">
  <h3>2. Analog reconstruction</h3>
  <img id="reconstruction" alt="Reconstruction">
 </div>

 <div class="panel">
  <h3>3. Spatial residual</h3>
  <img id="residual" alt="Residual">
 </div>

 <div class="panel">
  <h3>4. Analog ladder spectrum</h3>
  <canvas id="spectrum" width="900" height="420"></canvas>
  <small>Solid lines: target spectrum. Dashed lines: fitted spectrum.</small>
 </div>

 <div class="panel">
  <h3>Selected generative structures</h3>
  <div id="generators"></div>
 </div>

 <div class="panel">
  <h3>Discovery history</h3>
  <div id="events"></div>
 </div>
</div>

<script>
let revision=-1;
let eventCount=0;

function drawSpectrum(data){
    const c=document.getElementById("spectrum");
    const ctx=c.getContext("2d");
    const w=c.width,h=c.height;

    ctx.clearRect(0,0,w,h);
    ctx.fillStyle="#111923";
    ctx.fillRect(0,0,w,h);

    if(!data || !data.length) return;

    const max=Math.max(
        ...data.flatMap(d=>[
            ...d.target,...d.fitted
        ]),1e-12
    );

    const colors=["#54b9ff","#ffb65c","#6de0a5"];

    ctx.strokeStyle="#3a4655";
    ctx.lineWidth=1;

    for(let i=0;i<5;i++){
        const y=30+i*(h-70)/4;
        ctx.beginPath();
        ctx.moveTo(55,y);
        ctx.lineTo(w-20,y);
        ctx.stroke();
    }

    for(let ch=0;ch<3;ch++){
        for(const fitted of [false,true]){
            ctx.beginPath();
            ctx.strokeStyle=colors[ch];
            ctx.lineWidth=fitted?2:1.4;
            ctx.setLineDash(fitted?[7,5]:[]);

            data.forEach((d,i)=>{
                const x=55+i*(w-80)/(data.length-1);
                const value=fitted?d.fitted[ch]:d.target[ch];
                const y=h-30-(value/max)*(h-65);

                if(i===0) ctx.moveTo(x,y);
                else ctx.lineTo(x,y);
            });

            ctx.stroke();
        }
    }

    ctx.setLineDash([]);
    ctx.fillStyle="#aebdce";
    ctx.font="12px Segoe UI";
    ctx.fillText("Spatial frequency →",w/2,h-5);
    ctx.fillText("Power",8,18);
}

function updateGenerators(list){
    const root=document.getElementById("generators");
    root.innerHTML="";

    list.forEach((g,i)=>{
        const line=document.createElement("div");
        line.style.padding="7px";
        line.style.borderBottom="1px solid #354456";

        line.textContent=
          "#"+(i+1)+
          "  rho="+g.rho.toFixed(5)+
          "  gamma="+g.gamma.toFixed(5)+
          "  n="+g.n+
          "  tau="+g.tau+
          "  coeff="+g.coefficients.map(v=>v.toFixed(5)).join("/");

        root.appendChild(line);
    });
}

function updateEvents(list){
    const root=document.getElementById("events");
    root.innerHTML="";

    [...list].reverse().forEach(e=>{
        const line=document.createElement("div");
        line.style.padding="5px";
        line.textContent=
          "Stage "+e.stage+
          " | rho="+e.rho+
          " | gamma="+e.gamma+
          " | n="+e.n+
          " | tau="+e.tau+
          " | MSE="+e.mse.toFixed(3)+
          " | bytes="+e.model_bytes;
        root.appendChild(line);
    });
}

async function poll(){
    try{
        const r=await fetch("/state");
        const s=await r.json();

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

        document.getElementById("mse").textContent=
            s.mse===null?"—":s.mse;

        document.getElementById("spectral").textContent=
            s.spectral_error===null?"—":s.spectral_error;

        document.getElementById("bytes").textContent=
            s.model_bytes.toLocaleString();

        document.getElementById("bpp").textContent=
            s.bpp_model===null?"—":s.bpp_model;

        document.getElementById("status").textContent=s.status;

        document.getElementById("dimensions").textContent=
            s.width+" × "+s.height+
            " | seed vocabulary: "+
            s.seed_vocabulary.toLocaleString();

        if(s.revision!==revision){
            revision=s.revision;
            const suffix="?v="+revision;

            document.getElementById("reconstruction").src=
                "/view/reconstruction"+suffix;

            document.getElementById("residual").src=
                "/view/residual"+suffix;
        }

        drawSpectrum(s.spectrum);
        updateGenerators(s.selected);

        if(s.events.length!==eventCount){
            updateEvents(s.events);
            eventCount=s.events.length;
        }

    }catch(e){}
}

setInterval(poll,500);
poll();
</script>
</body>
</html>
"""


class Handler(BaseHTTPRequestHandler):

    def log_message(self,*args):
        pass

    def do_GET(self):
        path=urlparse(self.path).path

        if path=="/":
            data=HTML.encode()
            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 path=="/state":
            with LOCK:
                data=json.dumps(STATE).encode()

            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

        if path.startswith("/view/"):
            name=path.split("/")[-1]

            with LOCK:
                data=IMAGE_CACHE.get(name)

            if data is None:
                self.send_error(404)
                return

            self.send_response(200)
            self.send_header("Content-Type","image/jpeg")
            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)


# ============================================================
# Main
# ============================================================

def main():
    parser=argparse.ArgumentParser()

    parser.add_argument("image")

    parser.add_argument(
        "--seed-db",
        default="image_structures.sqlite3"
    )

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

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

    parser.add_argument(
        "--iterations",
        type=int,
        default=100
    )

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

    args=parser.parse_args()

    if not os.path.exists(args.image):
        raise SystemExit("Image not found: "+args.image)

    if args.bins<32:
        raise SystemExit("--bins must be at least 32")

    if args.stages<1:
        raise SystemExit("--stages must be positive")

    global SOURCE,RECONSTRUCTION,RESIDUAL

    image=Image.open(args.image)
    image=ImageOps.exif_transpose(image).convert("RGB")

    SOURCE=np.asarray(image,dtype=np.uint8)

    RECONSTRUCTION=np.full_like(SOURCE,127)
    RESIDUAL=SOURCE.copy()

    update_images()

    worker=threading.Thread(
        target=run_engine,
        args=(
            args.image,
            args.seed_db,
            args.stages,
            args.bins,
            args.iterations,
            args.model
        ),
        daemon=True
    )

    worker.start()

    server=ThreadingHTTPServer(
        (HOST,PORT),
        Handler
    )

    print()
    print("ANALOG FRACTAL WORKBENCH")
    print("========================")
    print("Image:",args.image)
    print("Seed database:",args.seed_db)
    print("Search stages:",args.stages)
    print("Radial bins:",args.bins)
    print("Joint fitting iterations:",args.iterations)
    print()
    print("Dashboard: http://127.0.0.1:8766")
    print("Model:",args.model)
    print("Press Ctrl+C to stop.")
    print()

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nStopping.")
    finally:
        server.shutdown()
        server.server_close()


if __name__=="__main__":
    main()
