
#!/usr/bin/env python3
"""
discover_image.py

Multi-scale visual structure discovery.

Finds recurring image structures across position and scale.

Identity:
    Exact equality of canonical, normalized 8x8 integer descriptors.

This is a visual-structure discovery backend, not yet a fractal
compression encoder.

Requires:
    py -m pip install Pillow

Usage:
    py discover_image.py photograph.jpg
    py discover_image.py photograph.jpg --max-side 1024
    py discover_image.py photograph.jpg --scales 8,16,32,64,128

Outputs:
    image_discoveries.jsonl
    image_structures.sqlite3

Existing RC discovery files are not modified.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import sqlite3
import time

from pathlib import Path
from PIL import Image


DESCRIPTOR_SIZE = 8


def canonical_d4(values):
    """Canonicalize an 8x8 descriptor under rotations/reflections."""
    n = DESCRIPTOR_SIZE
    grid = [values[i*n:(i+1)*n] for i in range(n)]
    variants = []

    for reflected in (False, True):
        source = [row[::-1] for row in grid] if reflected else grid

        current = source
        for _ in range(4):
            variants.append(bytes(
                value for row in current for value in row
            ))

            current = [
                [current[n-1-y][x] for y in range(n)]
                for x in range(n)
            ]

    return min(variants)


def descriptor_for_patch(image, x, y, size):
    """
    Convert a square patch to a normalized 8x8 integer descriptor.

    Normalization removes absolute brightness and contrast so that
    spatial patterns can recur under different lighting conditions.
    """
    patch = image.crop((x, y, x+size, y+size))
    small = patch.resize(
        (DESCRIPTOR_SIZE, DESCRIPTOR_SIZE),
        Image.Resampling.LANCZOS,
    )

    pixels = list(small.getdata())
    low = min(pixels)
    high = max(pixels)
    span = high - low

    if span == 0:
        normalized = bytes([0] * len(pixels))
    else:
        normalized = bytes(
            ((value - low) * 15 + span // 2) // span
            for value in pixels
        )

    return canonical_d4(normalized), low, high


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

    db.execute("""
        CREATE TABLE IF NOT EXISTS structures (
            structure_id TEXT PRIMARY KEY,
            descriptor BLOB NOT NULL,
            first_x INTEGER NOT NULL,
            first_y INTEGER NOT NULL,
            first_scale INTEGER NOT NULL,
            occurrences INTEGER NOT NULL DEFAULT 0,
            scale_counts TEXT NOT NULL DEFAULT '{}',
            intensity_min INTEGER NOT NULL,
            intensity_max INTEGER NOT NULL
        )
    """)

    db.execute("""
        CREATE TABLE IF NOT EXISTS sources (
            source_id TEXT PRIMARY KEY,
            filename TEXT NOT NULL,
            width INTEGER NOT NULL,
            height INTEGER NOT NULL,
            created REAL NOT NULL
        )
    """)

    db.execute("""
        CREATE TABLE IF NOT EXISTS observations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            source_id TEXT NOT NULL,
            structure_id TEXT NOT NULL,
            x INTEGER NOT NULL,
            y INTEGER NOT NULL,
            scale INTEGER NOT NULL
        )
    """)

    db.execute("""
        CREATE INDEX IF NOT EXISTS observation_structure
        ON observations(structure_id)
    """)

    db.commit()
    return db


def insert_observation(
    db, discoveries, source_id, descriptor,
    x, y, scale, low, high
):
    sid = hashlib.sha256(descriptor).hexdigest()

    row = db.execute(
        "SELECT occurrences, scale_counts FROM structures "
        "WHERE structure_id=?",
        (sid,),
    ).fetchone()

    if row is None:
        scale_counts = {str(scale): 1}

        db.execute("""
            INSERT INTO structures (
                structure_id, descriptor,
                first_x, first_y, first_scale,
                occurrences, scale_counts,
                intensity_min, intensity_max
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            sid, descriptor, x, y, scale,
            1, json.dumps(scale_counts), low, high,
        ))

        discoveries.write(json.dumps({
            "structure_id": sid,
            "domain": "image",
            "identity": "exact_canonical_integer_descriptor",
            "descriptor_size": DESCRIPTOR_SIZE,
            "descriptor_bits": 4,
            "first_observation": {
                "x": x,
                "y": y,
                "scale": scale,
            },
            "source_id": source_id,
            "descriptor": list(descriptor),
        }) + "\n")

        return True

    occurrences, old_counts = row
    scale_counts = json.loads(old_counts)
    scale_counts[str(scale)] = scale_counts.get(str(scale), 0) + 1

    db.execute("""
        UPDATE structures
        SET occurrences=?,
            scale_counts=?,
            intensity_min=MIN(intensity_min, ?),
            intensity_max=MAX(intensity_max, ?)
        WHERE structure_id=?
    """, (
        occurrences + 1,
        json.dumps(scale_counts, sort_keys=True),
        low, high, sid,
    ))

    return False


def discover(
    image_path,
    database_path,
    discoveries_path,
    scales,
    max_side,
    max_patches,
):
    image_path = Path(image_path).resolve()

    if not image_path.exists():
        raise FileNotFoundError(image_path)

    source_hash = hashlib.sha256()
    with image_path.open("rb") as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b""):
            source_hash.update(chunk)

    source_id = source_hash.hexdigest()

    image = Image.open(image_path).convert("L")
    original_width, original_height = image.size

    if max(image.size) > max_side:
        image.thumbnail(
            (max_side, max_side),
            Image.Resampling.LANCZOS,
        )

    width, height = image.size

    db = initialize_database(database_path)

    db.execute("""
        INSERT OR IGNORE INTO sources
        (source_id, filename, width, height, created)
        VALUES (?, ?, ?, ?, ?)
    """, (
        source_id, image_path.name,
        original_width, original_height, time.time(),
    ))

    db.commit()

    print("IMAGE STRUCTURE DISCOVERY")
    print(f"Input: {image_path}")
    print(f"Source ID: {source_id}")
    print(f"Original dimensions: {original_width} x {original_height}")
    print(f"Analysis dimensions: {width} x {height}")
    print(f"Scales: {scales}")
    print()

    total_observations = 0
    total_new = 0

    with discoveries_path.open("a", encoding="utf-8") as discoveries:
        for scale in scales:
            if scale > min(width, height):
                continue

            stride = max(1, 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 = (len(positions) + max_patches - 1) // max_patches
                positions = positions[::step]

            new_at_scale = 0

            for index, (x, y) in enumerate(positions, 1):
                descriptor, low, high = descriptor_for_patch(
                    image, x, y, scale
                )

                is_new = insert_observation(
                    db, discoveries, source_id,
                    descriptor, x, y, scale, low, high,
                )

                db.execute("""
                    INSERT INTO observations
                    (source_id, structure_id, x, y, scale)
                    VALUES (?, ?, ?, ?, ?)
                """, (
                    source_id,
                    hashlib.sha256(descriptor).hexdigest(),
                    x, y, scale,
                ))

                total_observations += 1

                if is_new:
                    new_at_scale += 1
                    total_new += 1

                if index % 500 == 0:
                    db.commit()
                    discoveries.flush()

            db.commit()
            discoveries.flush()

            print(
                f"scale={scale:4d} "
                f"patches={len(positions):8d} "
                f"new_structures={new_at_scale:8d} "
                f"total_observations={total_observations:9d}"
            )

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

    repeated = db.execute("""
        SELECT COUNT(*) FROM structures WHERE occurrences > 1
    """).fetchone()[0]

    cross_scale = db.execute("""
        SELECT COUNT(*) FROM structures
        WHERE json_array_length(json_group_array(scale_counts)) > 1
    """).fetchone()[0] if False else None

    db.close()

    print()
    print("IMAGE DISCOVERY COMPLETE")
    print(f"Observations: {total_observations}")
    print(f"New structures in this run: {total_new}")
    print(f"Unique structures in database: {unique}")
    print(f"Repeated structures: {repeated}")
    print(f"Database: {database_path}")
    print(f"Discovery log: {discoveries_path}")


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

    parser.add_argument("image")
    parser.add_argument("--database", default="image_structures.sqlite3")
    parser.add_argument("--discoveries", default="image_discoveries.jsonl")
    parser.add_argument("--max-side", type=int, default=1024)
    parser.add_argument("--max-patches", type=int, default=100000)
    parser.add_argument(
        "--scales",
        default="8,16,32,64,128",
    )

    args = parser.parse_args()

    scales = sorted(set(
        int(value) for value in args.scales.split(",")
    ))

    if not scales or any(value < 8 for value in scales):
        parser.error("All scales must be at least 8 pixels")

    if args.max_side < 8 or args.max_patches < 1:
        parser.error("--max-side must be >= 8 and --max-patches >= 1")

    discover(
        args.image,
        Path(args.database),
        Path(args.discoveries),
        scales,
        args.max_side,
        args.max_patches,
    )


if __name__ == "__main__":
    main()
