
#!/usr/bin/env python3
"""
IMAGE RELATION DISCOVERY
========================

Preserves image_structures.sqlite3 as the seed vocabulary.
Discovers approximate visual transformations and four-part compositions.
Runs a live browser dashboard at http://127.0.0.1:8766.

Requires:
    py -m pip install Pillow

Run:
    py discover_image_relations.py photograph.jpg

Optional:
    py discover_image_relations.py photograph.jpg --db image_structures.sqlite3
"""

import argparse
import io
import json
import math
import os
import sqlite3
import threading
import time
import hashlib
from collections import defaultdict
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse

from PIL import Image, ImageOps

HOST = "127.0.0.1"
PORT = 8766
DESCRIPTOR_SIZE = 8
MATCH_LIMIT = 8
CANDIDATE_LIMIT = 96
MATCH_THRESHOLD = 0.105

LOCK = threading.RLock()
STATE = {
    "status": "Starting",
    "processed": 0,
    "matches": 0,
    "compositions": 0,
    "vocabulary": 0,
    "total": 0,
    "current": None,
    "events": [],
    "started": time.time(),
}

TILES = {}
SOURCE_IMAGE = None


# ------------------------------------------------------------
# Descriptor generation
# ------------------------------------------------------------

def descriptor(image):
    """Return a normalized 8x8 integer descriptor."""
    small = image.convert("L").resize(
        (DESCRIPTOR_SIZE, DESCRIPTOR_SIZE),
        Image.Resampling.LANCZOS
    )
    values = list(small.getdata())

    lo = min(values)
    hi = max(values)
    span = hi - lo

    if span == 0:
        return bytes([0] * 64)

    return bytes(
        min(15, max(0, round((v - lo) * 15 / span)))
        for v in values
    )


def canonical(data):
    """Canonicalize a descriptor under rotations and reflections."""
    grid = [list(data[y * 8:(y + 1) * 8]) for y in range(8)]
    variants = []

    for reflected in (False, True):
        g = [row[:] for row in grid]

        if reflected:
            g = [row[::-1] for row in g]

        for _ in range(4):
            variants.append(bytes(v for row in g for v in row))
            g = [list(row) for row in zip(*g[::-1])]

    return min(variants)


def coarse(data):
    """Downsample 8x8 descriptor to a 4x4 signature."""
    result = []

    for y in range(4):
        for x in range(4):
            vals = [
                data[(y * 2 + dy) * 8 + x * 2 + dx]
                for dy in range(2)
                for dx in range(2)
            ]
            result.append(sum(vals) // 4)

    return bytes(result)


def distance(a, b):
    """Normalized mean absolute descriptor difference."""
    return sum(abs(x - y) for x, y in zip(a, b)) / (64 * 15)


# ------------------------------------------------------------
# Existing vocabulary
# ------------------------------------------------------------

def load_vocabulary(path):
    db = sqlite3.connect(path)
    db.row_factory = sqlite3.Row

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

    if "structures" not in tables:
        raise RuntimeError(
            "The seed database has no 'structures' table."
        )

    columns = {
        row["name"]
        for row in db.execute("PRAGMA table_info(structures)")
    }

    descriptor_col = next(
        (name for name in ("descriptor", "signature", "data")
         if name in columns),
        None
    )

    if descriptor_col is None:
        raise RuntimeError(
            "Could not locate descriptor column in structures table. "
            f"Available columns: {sorted(columns)}"
        )

    rows = db.execute(
        f'SELECT rowid AS structure_id, "{descriptor_col}" AS descriptor '
        "FROM structures"
    ).fetchall()

    vocabulary = {}
    buckets = defaultdict(list)

    for row in rows:
        raw = row["descriptor"]

        if raw is None:
            continue

        try:
            if isinstance(raw, str):
                parsed = json.loads(raw)
                raw = bytes(parsed)
            else:
                raw = bytes(raw)
        except Exception:
            continue

        if len(raw) != 64:
            continue

        data = canonical(raw)
        sid = int(row["structure_id"])

        vocabulary[sid] = data
        buckets[coarse(data)].append((sid, data))

    db.close()

    if not vocabulary:
        raise RuntimeError(
            "No 64-byte descriptors were loaded. "
            "The database descriptor format may differ from expected."
        )

    return vocabulary, buckets


def nearest(data, buckets):
    """Find approximate vocabulary matches using a coarse index."""
    key = coarse(data)
    candidates = buckets.get(key, [])

    # A small neighborhood of nearby coarse signatures.
    if not candidates:
        return []

    if len(candidates) > CANDIDATE_LIMIT:
        step = max(1, len(candidates) // CANDIDATE_LIMIT)
        candidates = candidates[::step][:CANDIDATE_LIMIT]

    scored = []

    for sid, candidate in candidates:
        score = distance(data, candidate)
        scored.append((score, sid))

    scored.sort()
    return scored[:MATCH_LIMIT]


# ------------------------------------------------------------
# Separate relationship database
# ------------------------------------------------------------

def initialize_output(path):
    db = sqlite3.connect(path)

    db.executescript("""
        CREATE TABLE IF NOT EXISTS relations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            kind TEXT NOT NULL,
            x INTEGER,
            y INTEGER,
            scale INTEGER,
            score REAL,
            source_structure INTEGER,
            child_structures TEXT,
            created REAL
        );

        CREATE TABLE IF NOT EXISTS runs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            image TEXT,
            started REAL,
            finished REAL,
            observations INTEGER,
            matches INTEGER,
            compositions INTEGER
        );
    """)

    db.commit()
    db.close()


def save_relation(path, kind, x, y, scale, score,
                  source_structure=None, children=None):
    db = sqlite3.connect(path)

    db.execute("""
        INSERT INTO relations
        (kind, x, y, scale, score, source_structure,
         child_structures, created)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    """, (
        kind, x, y, scale, score,
        source_structure,
        json.dumps(children) if children else None,
        time.time()
    ))

    db.commit()
    db.close()


# ------------------------------------------------------------
# Live discovery
# ------------------------------------------------------------

def publish(event):
    with LOCK:
        STATE["events"].append(event)

        # Keep browser payload bounded.
        if len(STATE["events"]) > 500:
            STATE["events"] = STATE["events"][-500:]


def make_tile(image, key):
    output = io.BytesIO()
    image.convert("RGB").save(output, format="JPEG", quality=78)

    with LOCK:
        TILES[key] = output.getvalue()


def analyze(image_path, seed_db, output_db, scales, max_patches):
    global SOURCE_IMAGE

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

    vocabulary, buckets = load_vocabulary(seed_db)

    with LOCK:
        STATE["vocabulary"] = len(vocabulary)
        STATE["status"] = "Discovering"
        STATE["width"], STATE["height"] = image.size

    initialize_output(output_db)

    run_db = sqlite3.connect(output_db)
    cur = run_db.execute(
        "INSERT INTO runs(image, started) VALUES (?, ?)",
        (os.path.abspath(image_path), time.time())
    )
    run_id = cur.lastrowid
    run_db.commit()
    run_db.close()

    width, height = image.size
    total = 0

    for scale in scales:
        if scale > width or scale > height:
            continue

        stride = max(4, scale // 2)
        positions = [
            (x, y)
            for y in range(0, height - scale + 1, stride)
            for x in range(0, width - scale + 1, stride)
        ]

        if len(positions) > max_patches:
            step = math.ceil(len(positions) / max_patches)
            positions = positions[::step]

        total += len(positions)

    with LOCK:
        STATE["total"] = total

    for scale in scales:
        if scale > width or scale > height:
            continue

        stride = max(4, scale // 2)
        positions = [
            (x, y)
            for y in range(0, height - scale + 1, stride)
            for x in range(0, width - scale + 1, stride)
        ]

        if len(positions) > max_patches:
            step = math.ceil(len(positions) / max_patches)
            positions = positions[::step]

        for x, y in positions:
            patch = image.crop((x, y, x + scale, y + scale))
            desc = canonical(descriptor(patch))

            matches = nearest(desc, buckets)
            best = matches[0] if matches else None

            event = {
                "kind": "region",
                "x": x,
                "y": y,
                "scale": scale,
                "score": round(best[0], 4) if best else None,
                "structure": best[1] if best else None,
                "matches": [
                    {"id": sid, "score": round(score, 4)}
                    for score, sid in matches
                ],
            }

            tile_id = f"{scale}_{x}_{y}"
            make_tile(patch, tile_id)
            event["tile"] = tile_id

            if best and best[0] <= MATCH_THRESHOLD:
                event["kind"] = "transformation"
                with LOCK:
                    STATE["matches"] += 1

                save_relation(
                    output_db, "transformation",
                    x, y, scale, best[0],
                    source_structure=best[1]
                )

            publish(event)

            # Four-way composition: identify vocabulary matches
            # for each quadrant of the current image region.
            half = scale // 2

            if half >= 8:
                quadrants = [
                    patch.crop((0, 0, half, half)),
                    patch.crop((half, 0, scale, half)),
                    patch.crop((0, half, half, scale)),
                    patch.crop((half, half, scale, scale)),
                ]

                child_ids = []
                child_scores = []

                for q in quadrants:
                    qdesc = canonical(descriptor(q))
                    qmatches = nearest(qdesc, buckets)

                    if qmatches:
                        child_scores.append(qmatches[0][0])
                        child_ids.append(qmatches[0][1])
                    else:
                        child_scores.append(1.0)
                        child_ids.append(None)

                composition_score = sum(child_scores) / 4

                if (
                    all(v is not None for v in child_ids)
                    and composition_score <= MATCH_THRESHOLD
                ):
                    with LOCK:
                        STATE["compositions"] += 1

                    publish({
                        "kind": "composition",
                        "x": x,
                        "y": y,
                        "scale": scale,
                        "score": round(composition_score, 4),
                        "children": child_ids,
                    })

                    save_relation(
                        output_db, "composition",
                        x, y, scale, composition_score,
                        children=child_ids
                    )

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

    run_db = sqlite3.connect(output_db)
    run_db.execute("""
        UPDATE runs SET finished=?, observations=?,
        matches=?, compositions=? WHERE id=?
    """, (
        time.time(),
        STATE["processed"],
        STATE["matches"],
        STATE["compositions"],
        run_id
    ))
    run_db.commit()
    run_db.close()

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


# ------------------------------------------------------------
# Browser dashboard
# ------------------------------------------------------------

HTML = r"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Image Fractal Discovery</title>
<style>
body {
    background:#10141b; color:#e8edf5;
    font-family:Segoe UI,Arial,sans-serif;
    margin:0; padding:18px;
}
h2 { margin:0 0 12px 0; }
.grid {
    display:grid;
    grid-template-columns:minmax(400px, 2fr) minmax(300px, 1fr);
    gap:16px;
}
.panel {
    background:#1a222d; border:1px solid #354252;
    border-radius:9px; padding:12px; min-width:0;
}
canvas {
    width:100%; height:auto; background:#05070a;
    border-radius:5px;
}
.stats {
    display:grid; grid-template-columns:repeat(3,1fr);
    gap:8px; margin-bottom:12px;
}
.stat {
    background:#222e3b; border-radius:7px;
    padding:10px; text-align:center;
}
.stat strong { display:block; font-size:23px; }
.stat span { color:#9eafc2; font-size:12px; }
#tiles {
    display:grid; grid-template-columns:repeat(3,1fr);
    gap:7px; max-height:650px; overflow:auto;
}
.tile {
    background:#273442; padding:5px;
    border-radius:5px; font-size:11px;
}
.tile img { width:100%; display:block; }
#log {
    max-height:180px; overflow:auto;
    font:12px Consolas,monospace; color:#b8c9dc;
}
small { color:#9eafc2; }
</style>
</head>
<body>
<h2>IMAGE / FRACTAL DISCOVERY</h2>
<div class="stats">
 <div class="stat"><strong id="processed">0</strong><span>Regions analyzed</span></div>
 <div class="stat"><strong id="matches">0</strong><span>Transform matches</span></div>
 <div class="stat"><strong id="compositions">0</strong><span>Compositions</span></div>
</div>
<div class="stats">
 <div class="stat"><strong id="vocabulary">0</strong><span>Seed structures</span></div>
 <div class="stat"><strong id="progress">0%</strong><span>Progress</span></div>
 <div class="stat"><strong id="status">Starting</strong><span>Engine state</span></div>
</div>
<div class="grid">
 <div class="panel">
  <h3>Original image / active region</h3>
  <canvas id="main" width="1000" height="750"></canvas>
  <p><small id="active">Waiting for discovery...</small></p>
  <h3>Discovery activity</h3>
  <div id="log"></div>
 </div>
 <div class="panel">
  <h3>Discovered image structures</h3>
  <div id="tiles"></div>
 </div>
</div>
<script>
const canvas=document.getElementById("main");
const ctx=canvas.getContext("2d");
const img=new Image();
img.src="/image";
img.onload=()=>draw();

let events=[];
let lastTile="";
let current=null;

function draw(){
    if(!img.complete || !img.naturalWidth) return;
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.drawImage(img,0,0,canvas.width,canvas.height);
    if(current){
        const sx=canvas.width/img.naturalWidth;
        const sy=canvas.height/img.naturalHeight;
        ctx.lineWidth=3;
        ctx.strokeStyle="#00ffad";
        ctx.strokeRect(
            current.x*sx,current.y*sy,
            current.scale*sx,current.scale*sy
        );
    }
}

function addTile(e){
    if(!e.tile || e.tile===lastTile) return;
    lastTile=e.tile;
    const div=document.createElement("div");
    div.className="tile";
    const im=document.createElement("img");
    im.src="/tile/"+e.tile;
    const label=document.createElement("div");
    label.textContent=
      e.kind+" | "+e.scale+"px | score "+e.score;
    div.appendChild(im);
    div.appendChild(label);
    const root=document.getElementById("tiles");
    root.prepend(div);
    while(root.children.length>90) root.lastChild.remove();
}

function addLog(e){
    const line=document.createElement("div");
    if(e.kind==="composition"){
        line.textContent=
          "COMPOSE "+e.scale+"px ["+e.children.join(",")+"]";
    } else {
        line.textContent=
          e.kind.toUpperCase()+" "+e.scale+"px @ "+
          e.x+","+e.y+" score="+e.score+
          " structure="+e.structure;
    }
    const log=document.getElementById("log");
    log.prepend(line);
    while(log.children.length>100) log.lastChild.remove();
}

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

        document.getElementById("processed").textContent=s.processed;
        document.getElementById("matches").textContent=s.matches;
        document.getElementById("compositions").textContent=s.compositions;
        document.getElementById("vocabulary").textContent=s.vocabulary;
        document.getElementById("status").textContent=s.status;
        document.getElementById("progress").textContent=
          s.total ? (100*s.processed/s.total).toFixed(1)+"%" : "0%";

        if(s.current){
            current=s.current;
            document.getElementById("active").textContent=
              "Analyzing "+s.current.scale+"px region at "+
              s.current.x+", "+s.current.y;
            draw();
        }

        for(const e of s.events){
            const key=JSON.stringify(e);
            if(!events.includes(key)){
                events.push(key);
                addLog(e);
                addTile(e);
            }
        }
        if(events.length>600) events=events.slice(-300);
    }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 == "/image":
            output = io.BytesIO()
            SOURCE_IMAGE.save(output, format="JPEG", quality=90)
            data = output.getvalue()

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

        if path.startswith("/tile/"):
            key = path.split("/tile/", 1)[1]

            with LOCK:
                data = TILES.get(key)

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

            self.send_response(200)
            self.send_header("Content-Type", "image/jpeg")
            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("--db", default="image_structures.sqlite3")
    parser.add_argument("--output", default="image_relations.sqlite3")
    parser.add_argument(
        "--scales", default="8,16,32,64,128"
    )
    parser.add_argument(
        "--max-patches", type=int, default=12000
    )
    args = parser.parse_args()

    scales = sorted({
        int(v) for v in args.scales.split(",") if v.strip()
    })

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

    if not os.path.exists(args.db):
        raise SystemExit("Seed database not found: " + args.db)

    # Load image before serving so /image is immediately available.
    global SOURCE_IMAGE
    SOURCE_IMAGE = Image.open(args.image)
    SOURCE_IMAGE = ImageOps.exif_transpose(SOURCE_IMAGE).convert("RGB")

    worker = threading.Thread(
        target=analyze,
        args=(
            args.image, args.db, args.output,
            scales, args.max_patches
        ),
        daemon=True
    )
    worker.start()

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

    print("IMAGE RELATION DISCOVERY")
    print("Seed database:", args.db)
    print("Output database:", args.output)
    print("Dashboard: http://127.0.0.1:" + str(PORT))
    print("Press Ctrl+C to stop.")

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


if __name__ == "__main__":
    main()
