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

Whole-image fractal encoding, iterative decoding, residual discovery,
and live browser visualization.

Preserves image_structures.sqlite3.
Reads its existing structures as the seed vocabulary.

Outputs:
    image_fractal_model.json
    image_fractal_workbench.sqlite3

Dashboard:
    http://127.0.0.1:8766

Run:
    py image_fractal_workbench.py photograph.jpg

Optional:
    py image_fractal_workbench.py photograph.jpg --range 32 --stages 3
"""

import argparse
import io
import json
import math
import os
import sqlite3
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

LOCK = threading.RLock()

STATE = {
    "status": "Starting",
    "stage": 0,
    "stages": 0,
    "processed": 0,
    "total": 0,
    "matches": 0,
    "mse": None,
    "bpp": None,
    "seed_vocabulary": 0,
    "range_size": 32,
    "current": None,
    "events": [],
    "revision": 0,
}

SOURCE = None
RECONSTRUCTION = None
RESIDUAL = None
FRACTAL_MAP = None

IMAGE_CACHE = {}

MODEL = {
    "stages": [],
    "image_width": 0,
    "image_height": 0,
    "range_size": 32,
    "seed_vocabulary": 0,
}


# ============================================================
# Image utilities
# ============================================================

def pil_resize(array, width, height):
    array = np.clip(array, 0, 255).astype(np.uint8)
    return np.asarray(
        Image.fromarray(array).resize(
            (width, height),
            Image.Resampling.BILINEAR
        ),
        dtype=np.float32
    )


def pad_image(image, block):
    h, w, _ = image.shape

    ph = math.ceil(h / block) * block
    pw = math.ceil(w / block) * block

    if ph == h and pw == w:
        return image.copy()

    return np.pad(
        image,
        ((0, ph - h), (0, pw - w), (0, 0)),
        mode="reflect"
    )


def orient(array, index):
    """
    Eight dihedral orientations.
    First four rotations, then horizontal reflection + rotations.
    """
    if index >= 4:
        array = np.flip(array, axis=1)
        index -= 4

    return np.rot90(array, index).copy()


def grayscale(array):
    return (
        0.299 * array[..., 0]
        + 0.587 * array[..., 1]
        + 0.114 * array[..., 2]
    )


def descriptor(array):
    """A coarse 4x4 descriptor for candidate indexing only."""
    gray = grayscale(array)
    small = pil_resize(gray, 4, 4)
    return small.reshape(-1)


def image_bytes(array, quality=88):
    output = io.BytesIO()
    Image.fromarray(
        np.clip(array, 0, 255).astype(np.uint8)
    ).save(output, format="JPEG", quality=quality)
    return output.getvalue()


def update_image_cache():
    global IMAGE_CACHE

    with LOCK:
        if SOURCE is not None:
            IMAGE_CACHE["original"] = image_bytes(SOURCE)

        if RECONSTRUCTION is not None:
            IMAGE_CACHE["reconstruction"] = image_bytes(
                RECONSTRUCTION
            )

        if RESIDUAL is not None:
            IMAGE_CACHE["residual"] = image_bytes(RESIDUAL)

        if FRACTAL_MAP is not None:
            IMAGE_CACHE["map"] = image_bytes(FRACTAL_MAP)


def residual_visual(original, reconstruction):
    """
    Signed residual display:
      positive error -> red
      negative error -> blue
      zero error -> black
    """
    delta = original.astype(np.float32) - reconstruction.astype(
        np.float32
    )

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

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

    output = np.zeros_like(original, dtype=np.float32)

    positive = np.maximum(delta.mean(axis=2), 0)
    negative = np.maximum(-delta.mean(axis=2), 0)

    output[..., 0] = normalized.mean(axis=2) * 255 * (
        positive > negative
    )

    output[..., 2] = normalized.mean(axis=2) * 255 * (
        negative >= positive
    )

    output[..., 1] = normalized.mean(axis=2) * 35

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


# ============================================================
# Seed vocabulary
# ============================================================

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

    db = sqlite3.connect(path)

    try:
        tables = {
            row[0] for row in db.execute(
                "SELECT name FROM sqlite_master WHERE type='table'"
            )
        }

        if "structures" not in tables:
            return 0

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

    finally:
        db.close()


# ============================================================
# Fractal domain collection
# ============================================================

def build_domains(source, block):
    """
    Each domain is a 2*block square from the source image.
    It is reduced to block x block.

    Domains overlap by half a range block.
    """
    h, w, _ = source.shape
    domain_size = block * 2
    step = block // 2

    domains = []
    descriptors = []

    for y in range(0, h - domain_size + 1, step):
        for x in range(0, w - domain_size + 1, step):

            crop = source[
                y:y + domain_size,
                x:x + domain_size
            ]

            reduced = pil_resize(crop, block, block)

            domains.append((x, y, reduced))
            descriptors.append(descriptor(reduced))

    if not domains:
        raise RuntimeError(
            "Image is too small for the selected range size."
        )

    return domains, np.asarray(descriptors, dtype=np.float32)


def fit_affine(domain, target):
    """
    Per-channel least-squares affine mapping:

        target ~= a * domain + b

    Contrast is constrained to [-0.85, +0.85].
    """
    x = domain.reshape(-1, 3)
    y = target.reshape(-1, 3)

    xm = x.mean(axis=0)
    ym = y.mean(axis=0)

    variance = np.mean((x - xm) ** 2, axis=0)
    covariance = np.mean(
        (x - xm) * (y - ym),
        axis=0
    )

    a = covariance / np.maximum(variance, 1e-6)
    a = np.clip(a, -0.85, 0.85)

    b = ym - a * xm

    predicted = x * a + b
    error = float(np.mean((predicted - y) ** 2))

    return a, b, error


# ============================================================
# Fractal encoder
# ============================================================

def encode_fractal(source, block, stage):
    """
    Globally searches domain-to-range mappings.

    The image is represented by a complete set of transformations.
    The range blocks tile the entire image; they are not an
    independent 8x8 motif catalog.

    The search compares actual pixel data.
    """
    h, w, _ = source.shape

    domains, domain_descriptors = build_domains(source, block)

    range_positions = [
        (x, y)
        for y in range(0, h, block)
        for x in range(0, w, block)
    ]

    total = len(range_positions)

    records = []
    errors = []

    STATE["processed"] = 0
    STATE["total"] = total
    STATE["matches"] = 0
    STATE["status"] = f"Encoding stage {stage}"

    for index, (x, y) in enumerate(range_positions):

        target = source[y:y + block, x:x + block]

        if target.shape[:2] != (block, block):
            raise RuntimeError("Unexpected range block dimensions.")

        target_descriptor = descriptor(target)

        distances = np.mean(
            (domain_descriptors - target_descriptor) ** 2,
            axis=1
        )

        shortlist_count = min(8, len(domains))

        shortlist = np.argpartition(
            distances,
            shortlist_count - 1
        )[:shortlist_count]

        best = None

        for domain_index in shortlist:

            dx, dy, reduced = domains[int(domain_index)]

            for orientation in range(8):
                candidate = orient(reduced, orientation)

                a, b, error = fit_affine(candidate, target)

                if best is None or error < best["error"]:
                    best = {
                        "x": x,
                        "y": y,
                        "dx": dx,
                        "dy": dy,
                        "domain": int(domain_index),
                        "orientation": orientation,
                        "a": a.tolist(),
                        "b": b.tolist(),
                        "error": error,
                    }

        records.append(best)
        errors.append(best["error"])

        with LOCK:
            STATE["processed"] = index + 1
            STATE["current"] = {
                "x": x,
                "y": y,
                "block": block,
            }

            if index % 10 == 0:
                STATE["events"].append({
                    "stage": stage,
                    "x": x,
                    "y": y,
                    "error": round(best["error"], 3),
                })

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

    return {
        "block": block,
        "width": w,
        "height": h,
        "domains": len(domains),
        "records": records,
        "mean_encoding_error": float(np.mean(errors)),
    }


# ============================================================
# Fractal decoder
# ============================================================

def decode_fractal(model, initial=None, iterations=12):
    """
    Iterative fixed-point decoder.

    Every range block is regenerated from a domain in the
    previous complete image state.
    """
    block = model["block"]
    h = model["height"]
    w = model["width"]

    if initial is None:
        initial = np.full(
            (h, w, 3),
            127.5,
            dtype=np.float32
        )

    current = initial.copy()

    for iteration in range(iterations):

        output = np.zeros_like(current)

        for record in model["records"]:

            x = record["x"]
            y = record["y"]

            dx = record["dx"]
            dy = record["dy"]

            domain = current[
                dy:dy + block * 2,
                dx:dx + block * 2
            ]

            reduced = pil_resize(domain, block, block)

            transformed = orient(
                reduced,
                record["orientation"]
            )

            a = np.asarray(record["a"], dtype=np.float32)
            b = np.asarray(record["b"], dtype=np.float32)

            generated = transformed * a + b

            output[y:y + block, x:x + block] = generated

        current = np.clip(output, 0, 255)

        if iteration % 3 == 0:
            with LOCK:
                STATE["status"] = (
                    f"Decoding stage {STATE['stage']} "
                    f"iteration {iteration + 1}/{iterations}"
                )

    return current


# ============================================================
# Fractal map and model accounting
# ============================================================

def create_fractal_map(model):
    block = model["block"]
    h = model["height"]
    w = model["width"]

    result = np.zeros((h, w, 3), dtype=np.uint8)

    for record in model["records"]:

        identity = (
            f'{record["dx"]}:{record["dy"]}:'
            f'{record["orientation"]}'
        )

        digest = hashlib.sha256(
            identity.encode()
        ).digest()

        color = np.array(
            [digest[0], digest[1], digest[2]],
            dtype=np.uint8
        )

        x = record["x"]
        y = record["y"]

        result[y:y + block, x:x + block] = color

    return result


def estimate_bits(models):
    """
    Approximate model-description size.

    Per range:
      domain index
      3 orientation bits
      six 8-bit affine coefficients

    This is a model estimate, not a completed entropy-coded file.
    """
    total_bits = 0

    for model in models:
        domain_bits = math.ceil(
            math.log2(max(2, model["domains"]))
        )

        per_range = domain_bits + 3 + 6 * 8

        total_bits += (
            len(model["records"]) * per_range
        )

    return total_bits


def save_model(path, models, original_shape, block, seed_count):
    output = {
        "format": "IMAGE-FRACTAL-MODEL-1",
        "image_width": original_shape[1],
        "image_height": original_shape[0],
        "range_size": block,
        "seed_vocabulary": seed_count,
        "stages": models,
        "description": (
            "Iterated domain-range affine transformations. "
            "Residual stages are additive correction models."
        ),
    }

    with open(path, "w", encoding="utf-8") as f:
        json.dump(output, f, separators=(",", ":"))


# ============================================================
# Residual-driven iterative search
# ============================================================

def run_workbench(image_path, seed_db, range_size, stages,
                  iterations, model_path, database_path):

    global SOURCE, RECONSTRUCTION, RESIDUAL, FRACTAL_MAP

    original = Image.open(image_path)
    original = ImageOps.exif_transpose(original).convert("RGB")

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

    h0, w0 = SOURCE.shape[:2]

    padded = pad_image(SOURCE, range_size).astype(np.float32)

    h, w, _ = padded.shape

    seed_count = load_seed_count(seed_db)

    STATE["seed_vocabulary"] = seed_count
    STATE["range_size"] = range_size
    STATE["stages"] = stages

    with LOCK:
        RECONSTRUCTION = np.full(
            SOURCE.shape, 127, dtype=np.uint8
        )
        RESIDUAL = SOURCE.copy()
        FRACTAL_MAP = np.zeros_like(SOURCE)

    update_image_cache()

    db = sqlite3.connect(database_path)

    db.executescript("""
        CREATE TABLE IF NOT EXISTS stage_metrics (
            stage INTEGER PRIMARY KEY,
            mse REAL,
            residual_mse REAL,
            model_bits INTEGER,
            created REAL
        );

        CREATE TABLE IF NOT EXISTS transformations (
            stage INTEGER,
            range_x INTEGER,
            range_y INTEGER,
            domain_x INTEGER,
            domain_y INTEGER,
            orientation INTEGER,
            error REAL
        );
    """)

    db.commit()

    models = []
    reconstruction = np.full_like(padded, 127.0)

    for stage in range(stages):

        with LOCK:
            STATE["stage"] = stage + 1
            STATE["status"] = (
                "Preparing original image" if stage == 0
                else "Preparing residual"
            )

        if stage == 0:
            target = padded.copy()
            residual_scale = 1.0
        else:
            residual = padded - reconstruction

            residual_scale = max(
                float(np.max(np.abs(residual))) / 120.0,
                0.001
            )

            # Encode signed residual around neutral value 128.
            target = np.clip(
                128.0 + residual / residual_scale,
                0,
                255
            )

        model = encode_fractal(
            target,
            range_size,
            stage + 1
        )

        decoded = decode_fractal(
            model,
            iterations=iterations
        )

        if stage == 0:
            reconstruction = decoded
        else:
            correction = (
                decoded - 128.0
            ) * residual_scale

            reconstruction = np.clip(
                reconstruction + correction,
                0,
                255
            )

        model["stage"] = stage + 1
        model["residual_scale"] = residual_scale

        models.append(model)

        current_reconstruction = np.clip(
            reconstruction[:h0, :w0],
            0,
            255
        ).astype(np.uint8)

        current_residual = residual_visual(
            SOURCE,
            current_reconstruction
        )

        fractal_map = create_fractal_map(model)
        fractal_map = fractal_map[:h0, :w0]

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

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

        bits = estimate_bits(models)
        bpp = bits / (h0 * w0)

        with LOCK:
            RECONSTRUCTION = current_reconstruction
            RESIDUAL = current_residual
            FRACTAL_MAP = fractal_map

            STATE["mse"] = round(mse, 4)
            STATE["bpp"] = round(bpp, 4)
            STATE["revision"] += 1
            STATE["status"] = (
                f"Stage {stage + 1} complete"
            )

        update_image_cache()

        db.execute("""
            INSERT OR REPLACE INTO stage_metrics
            VALUES (?, ?, ?, ?, ?)
        """, (
            stage + 1,
            mse,
            mse,
            bits,
            time.time()
        ))

        db.execute(
            "DELETE FROM transformations WHERE stage=?",
            (stage + 1,)
        )

        db.executemany("""
            INSERT INTO transformations
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """, [
            (
                stage + 1,
                r["x"], r["y"],
                r["dx"], r["dy"],
                r["orientation"],
                r["error"]
            )
            for r in model["records"]
        ])

        db.commit()

        save_model(
            model_path,
            models,
            SOURCE.shape,
            range_size,
            seed_count
        )

        # Publish the current complete reconstruction.
        print(
            f"STAGE {stage + 1}/{stages} "
            f"MSE={mse:.4f} "
            f"estimated_bpp={bpp:.4f} "
            f"transforms={sum(len(m['records']) for m in models)}"
        )

    db.close()

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


# ============================================================
# Dashboard
# ============================================================

HTML = r"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Fractal Compression 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:5px 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:22px;
    overflow-wrap:anywhere;
}
.stat span { font-size:11px;color:#9baabd }
.views {
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
    gap:12px;
}
.panel {
    min-width:0;
    padding:12px;
    border-radius:9px;
    background:#1a222d;
    border:1px solid #354456;
}
img {
    display:block;
    width:100%;
    background:#080b10;
    border-radius:5px;
    image-rendering:auto;
}
#sourceCanvas {
    width:100%;
    height:auto;
    display:block;
}
#log {
    max-height:210px;
    overflow:auto;
    font:12px Consolas,monospace;
    color:#bdcce0;
}
.bar {
    height:9px;
    background:#303d4c;
    border-radius:8px;
    overflow:hidden;
    margin:7px 0;
}
#progressBar {
    height:100%;
    width:0%;
    background:#27d9a0;
}
@media(max-width:850px) {
    .views { grid-template-columns:1fr }
    .stats { grid-template-columns:repeat(2,1fr) }
}
</style>
</head>
<body>

<h2>WHOLE-IMAGE FRACTAL COMPRESSION WORKBENCH</h2>

<div class="stats">
 <div class="stat"><strong id="stage">0</strong><span>Residual stage</span></div>
 <div class="stat"><strong id="mse">—</strong><span>Reconstruction MSE</span></div>
 <div class="stat"><strong id="bpp">—</strong><span>Estimated model bits / pixel</span></div>
 <div class="stat"><strong id="transforms">0</strong><span>Selected transformations</span></div>
 <div class="stat"><strong id="seed">0</strong><span>Seed vocabulary</span></div>
</div>

<div class="panel">
 <div id="status">Starting engine...</div>
 <div class="bar"><div id="progressBar"></div></div>
 <small id="progress">0 / 0</small>
</div>

<br>

<div class="views">

 <div class="panel">
  <h3>1. Original image</h3>
  <canvas id="sourceCanvas"></canvas>
  <small>Current analysis region highlighted</small>
 </div>

 <div class="panel">
  <h3>2. Fractal reconstruction</h3>
  <img id="reconstruction" alt="Fractal reconstruction">
  <small>Actual output of the iterative decoder</small>
 </div>

 <div class="panel">
  <h3>3. Residual</h3>
  <img id="residual" alt="Signed reconstruction residual">
  <small>Red and blue indicate the direction of pixel error</small>
 </div>

 <div class="panel">
  <h3>4. Fractal transformation map</h3>
  <img id="map" alt="Fractal transformation map">
  <small>Each color identifies a selected domain/orientation mapping</small>
 </div>

</div>

<br>

<div class="panel">
 <h3>Discovery activity</h3>
 <div id="log"></div>
</div>

<script>
const sourceCanvas=document.getElementById("sourceCanvas");
const ctx=sourceCanvas.getContext("2d");
const sourceImage=new Image();
sourceImage.src="/view/original";

let lastRevision=-1;

sourceImage.onload=()=>{
    sourceCanvas.width=sourceImage.naturalWidth;
    sourceCanvas.height=sourceImage.naturalHeight;
    drawSource();
};

function drawSource(){
    if(!sourceImage.complete || !sourceImage.naturalWidth) return;

    ctx.clearRect(0,0,sourceCanvas.width,sourceCanvas.height);
    ctx.drawImage(sourceImage,0,0);

    fetch("/state").then(r=>r.json()).then(s=>{
        if(s.current){
            const c=s.current;
            ctx.lineWidth=2;
            ctx.strokeStyle="#00ffad";
            ctx.strokeRect(c.x,c.y,c.block,c.block);
        }
    }).catch(()=>{});
}

function refreshImages(revision){
    if(revision===lastRevision) return;
    lastRevision=revision;

    const suffix="?v="+revision;

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

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

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

function logEvents(events){
    const root=document.getElementById("log");

    for(const e of events){
        const line=document.createElement("div");
        line.textContent=
          "STAGE "+e.stage+
          " | RANGE "+e.x+","+e.y+
          " | error "+e.error;

        root.prepend(line);
    }

    while(root.children.length>150) root.lastChild.remove();
}

let eventCount=0;

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

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

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

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

        document.getElementById("seed").textContent=
            s.seed_vocabulary.toLocaleString();

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

        document.getElementById("progress").textContent=
            s.processed+" / "+s.total;

        const percent=s.total?
            100*s.processed/s.total:0;

        document.getElementById("progressBar").style.width=
            percent+"%";

        document.getElementById("transforms").textContent=
            s.stage * Math.ceil(s.total || 0);

        refreshImages(s.revision);
        drawSource();

        if(s.events.length>eventCount){
            logEvents(s.events.slice(eventCount));
            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("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 path == "/state":
            with LOCK:
                data = json.dumps(STATE).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

        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(
        "--range",
        type=int,
        default=32
    )

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

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

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

    parser.add_argument(
        "--database",
        default="image_fractal_workbench.sqlite3"
    )

    args = parser.parse_args()

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

    if args.range < 8 or args.range % 2:
        raise SystemExit("--range must be an even number >= 8")

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

    global SOURCE

    image = Image.open(args.image)
    image = ImageOps.exif_transpose(image).convert("RGB")
    SOURCE = np.asarray(image, dtype=np.uint8)

    STATE["status"] = "Starting dashboard"

    worker = threading.Thread(
        target=run_workbench,
        args=(
            args.image,
            args.seed_db,
            args.range,
            args.stages,
            args.iterations,
            args.model,
            args.database,
        ),
        daemon=True
    )

    worker.start()

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

    print()
    print("IMAGE FRACTAL WORKBENCH")
    print("=======================")
    print("Image:", args.image)
    print("Seed database:", args.seed_db)
    print("Range size:", args.range)
    print("Residual stages:", args.stages)
    print("Decoder iterations:", args.iterations)
    print()
    print("Dashboard: http://127.0.0.1:8766")
    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()
