"""Inventory TIFF-based camera RAWs, extract embedded JPEGs, and reconcile with the photo bank.

On the source host run `taskset -c 0-3 python3 - stream BANK` with this file as
stdin. Redirect stdout to a tar on the receiving computer. Then run locally
`python3 raw_previews.py reconcile TAR JPEG_DATASET DEST`. Camera times are local.
"""
import concurrent.futures
from datetime import datetime
import hashlib
import io
import json
import mmap
from pathlib import Path
import re
import struct
import subprocess
import sys
import tarfile
from collections import Counter


def digest(data):
    return hashlib.sha256(data).hexdigest()


def exif(b):
    order = {b"II": "<", b"MM": ">"}.get(b[:2])
    if not order or len(b) < 8:
        return {}

    def number(kind, off):
        return struct.unpack_from(order + kind, b, off)[0]

    def directory(off):
        tags = {}
        if off < 8 or off + 2 > len(b):
            return tags
        count = number("H", off)
        if count > 4096 or off + 2 + count * 12 > len(b):
            return tags
        for i in range(count):
            at = off + 2 + i * 12
            tag, kind, n = struct.unpack_from(order + "HHI", b, at)
            if tag not in {271, 272, 274, 34665, 36867, 36868, 37521, 42033}:
                continue
            if kind == 2 and 0 < n < 1024:
                start = at + 8 if n <= 4 else number("I", at + 8)
                tags[tag] = b[start:start + n].split(b"\0")[0].decode("ascii", "replace").strip()
            elif n == 1 and kind in (3, 4):
                tags[tag] = number("H" if kind == 3 else "I", at + 8)
        return tags

    tags = directory(number("I", 4))
    tags.update(directory(tags.get(34665, 0)))
    try:
        captured = datetime.strptime(tags.get(36867, ""), "%Y:%m:%d %H:%M:%S").isoformat()
    except ValueError:
        captured = None
    return {"capture": captured, "subsec": tags.get(37521), "camera": tags.get(272),
            "serial": tags.get(42033), "orientation": tags.get(274)}


def jpeg_segments(b, start=0):
    pos = start + 2
    while pos + 4 <= len(b) and b[pos] == 255:
        while pos < len(b) and b[pos] == 255:
            pos += 1
        if pos + 3 > len(b):
            return
        kind = b[pos]
        if kind in (0, 217, 216):
            return
        size = int.from_bytes(b[pos + 1:pos + 3], "big")
        end = pos + 1 + size
        if size < 2 or end > len(b):
            return
        yield kind, pos + 3, end
        if kind == 218:
            return
        pos = end


def jpeg_exif(path):
    with path.open("rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as b:
        for kind, start, end in jpeg_segments(b):
            if kind == 225 and b[start:start + 6] == b"Exif\0\0":
                return exif(b[start + 6:end])
    return {}


def largest_preview(b):
    best = (0, 0, 0, 0, 0)
    cursor = 0
    while (start := b.find(b"\xff\xd8\xff", cursor)) >= 0:
        cursor = start + 3
        width = height = 0
        for kind, data, end in jpeg_segments(b, start):
            if kind in (192, 193, 194) and end - data >= 6:
                height, width = struct.unpack_from(">HH", b, data + 1)
            if kind == 218 and width and height:
                last = b.find(b"\xff\xd9", end)
                if last > end:
                    best = max(best, (width * height, last + 2 - start, start, width, height))
                    cursor = last + 2
    if best[0] < 512 * 384:
        raise ValueError("no decodable large JPEG preview")
    _, size, offset, width, height = best
    return offset, size, width, height


def read_raw(path):
    row = {"original": str(Path(path.parent.name, path.name)), "raw_bytes": path.stat().st_size}
    row["horse"] = re.sub(r"\s+\(\d+\s+фото\)$", "", path.parent.name)
    with path.open("rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as b:
        row.update(exif(b))
        row["raw_sha256"] = digest(b)
        try:
            offset, size, width, height = largest_preview(b)
            embedded = b[offset:offset + size]
            row.update(embedded_offset=offset, embedded_length=size, embedded_width=width,
                       embedded_height=height, embedded_sha256=digest(embedded))
            orientations = ("Undefined", "TopLeft", "TopRight", "BottomRight", "BottomLeft",
                            "LeftTop", "RightTop", "RightBottom", "LeftBottom")
            orientation = row.get("orientation") or 1
            pixels = subprocess.run([
                "convert", "-limit", "thread", "1", "jpeg:-", "-orient", orientations[orientation],
                "-auto-orient", "-thumbnail", "1024x1024>", "-colorspace", "sRGB", "-strip",
                "-quality", "85", "jpeg:-"
            ], input=embedded, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True).stdout
            if not pixels.startswith(b"\xff\xd8") or not pixels.endswith(b"\xff\xd9"):
                raise ValueError("invalid converted JPEG")
            row["sha256"] = digest(pixels)
            row["file"] = "photos/" + row["sha256"] + ".jpg"
        except (subprocess.CalledProcessError, ValueError, IndexError) as err:
            row["error"] = str(err)
            pixels = None
    return row, pixels


def add(tar, name, data):
    info = tarfile.TarInfo(name)
    info.size = len(data)
    tar.addfile(info, io.BytesIO(data))


def stream(root):
    raw, jpeg = [], []
    for path in sorted(root.glob("*/*")):
        if path.suffix.lower() in {".cr2", ".nef"}:
            raw.append(path)
        if path.suffix.lower() in {".jpg", ".jpeg"}:
            jpeg.append({"original": str(path.relative_to(root)), **jpeg_exif(path)})
    if not raw or not jpeg:
        raise ValueError("empty RAW or JPEG collection")
    rows = []
    seen = set()
    with tarfile.open(fileobj=sys.stdout.buffer, mode="w|") as tar, concurrent.futures.ThreadPoolExecutor(2) as pool:
        for row, pixels in pool.map(read_raw, raw):
            if pixels and row["file"] not in seen:
                add(tar, row["file"], pixels)
                seen.add(row["file"])
            rows.append(row)
        for name, value in (("raw_sources.json", rows), ("jpeg_capture.json", jpeg)):
            add(tar, name, json.dumps(value, ensure_ascii=False).encode())
    print(f"{len(rows)} RAW, {len(seen)} distinct previews, {len(jpeg)} JPEG sources", file=sys.stderr)


def write_json(path, obj):
    path.write_text(json.dumps(obj, ensure_ascii=False, indent=2) + "\n")


def fingerprint(path):
    import numpy as np
    from PIL import Image
    from scipy.fft import dctn
    with Image.open(path) as image:
        image.load()
        rgb = np.asarray(image.convert("RGB").resize((32, 32), Image.Resampling.LANCZOS), dtype=float)
    grey = rgb @ np.array([0.299, 0.587, 0.114])
    low = dctn(grey, norm="ortho")[:8, :8].flatten()[1:]
    median = np.median(low)
    bits = sum(int(v > median) << i for i, v in enumerate(low))
    grey -= grey.mean()
    grey /= max(np.linalg.norm(grey), 1e-10)
    return bits, grey.flatten()


def reconcile(archive, old, dest):
    import numpy as np
    dest.mkdir(parents=True, exist_ok=True)
    (dest / "photos").mkdir(exist_ok=True)
    with tarfile.open(archive) as tar:
        raw = json.load(tar.extractfile("raw_sources.json"))
        jpeg = json.load(tar.extractfile("jpeg_capture.json"))
        for filename in sorted({r["file"] for r in raw if r.get("file")}):
            sha = Path(filename).stem
            if filename != "photos/" + sha + ".jpg" or not re.fullmatch(r"[0-9a-f]{64}", sha):
                raise ValueError(filename)
            data = tar.extractfile(filename).read()
            if digest(data) != sha:
                raise ValueError("bad archive checksum " + filename)
            (dest / filename).write_bytes(data)
    original = json.loads((old / "manifest.json").read_text())
    metadata = {r["original"]: r for r in jpeg}
    if set(metadata) != {r["original"] for r in original} or len(original) != len(jpeg):
        raise ValueError("JPEG source inventory does not match previous pilot")
    jpeg = [{**r, **metadata[r["original"]], "source": "jpeg"} for r in original]
    for r in raw:
        r["source"] = "raw"
        r["day"] = r["capture"][:10] if r.get("capture") else None
        r["day_source"] = "exif" if r["day"] else None
    write_json(dest / "jpeg_capture.json", jpeg)
    entries = jpeg + [r for r in raw if r.get("file")]
    # Cache by content digest. Exact JPEG copies may have multiple source names/labels.
    fingerprints = {}
    for r in entries:
        if r["sha256"] not in fingerprints:
            fingerprints[r["sha256"]] = fingerprint((old if r["source"] == "jpeg" else dest) / r["file"])
    bits = [fingerprints[r["sha256"]][0] for r in entries]
    matrices = np.asarray([fingerprints[r["sha256"]][1] for r in entries])
    corrs = matrices[len(jpeg):] @ matrices.T
    links = []
    nearest = []
    for i, row in enumerate(entries[len(jpeg):]):
        close = []
        for j, ref in enumerate(entries):
            if ref is row:
                continue
            dist = (bits[len(jpeg) + i] ^ bits[j]).bit_count()
            corr = float(corrs[i, j])
            stem = Path(row["original"]).stem.casefold() == Path(ref["original"]).stem.casefold()
            camera = bool(row.get("camera")) and row["camera"] == ref.get("camera")
            serial = bool(row.get("serial")) and row["serial"] == ref.get("serial")
            at = row.get("capture")
            timestamp = bool(at) and at == ref.get("capture")
            subsec = bool(row.get("subsec")) and row["subsec"] == ref.get("subsec")
            same_pixels = row["sha256"] == ref["sha256"]
            near = (dist <= 8 and corr >= 0.97) or (dist <= 12 and corr >= 0.99)
            possible = dist <= 14 and corr >= 0.93
            # Geometrically similar near-burst frames can have different timestamps and IDs.
            # Record them separately for temporal grouping / visual adjudication.
            risk = None
            if same_pixels or (timestamp and stem and camera and (subsec or near)):
                risk = "same_capture"
            elif (timestamp and (camera or serial)) or stem or near or possible:
                risk = "review"
            link = {"raw": row["original"], "reference": ref["original"], "source": ref["source"],
                    "reference_horse": ref["horse"], "reference_file": ref["file"],
                    "reference_capture": ref.get("capture"), "same_stem": stem,
                    "same_camera_model": camera, "same_serial": serial, "same_second": timestamp,
                    "same_subsec_field": subsec, "same_preview_bytes": same_pixels,
                    "same_horse": row["horse"] == ref["horse"], "phash_distance": dist,
                    "grayscale_correlation": round(corr, 5), "risk": risk}
            if risk:
                links.append(link)
            if j < len(jpeg):
                close.append(link)
        nearest.append(min(close, key=lambda x: (x["phash_distance"], -x["grayscale_correlation"])))
    by_orig = {}
    for link in links:
        by_orig.setdefault(link["raw"], []).append(link)
    for row in raw:
        related = by_orig.get(row["original"], [])
        if row.get("error") or not row["day"]:
            state = "missing_preview_or_exif"
        elif any(a["risk"] == "same_capture" and a["source"] == "jpeg" for a in related):
            state = "jpeg_duplicate"
        elif any(a["source"] == "jpeg" for a in related):
            state = "review_jpeg"
        elif related:
            state = "review_raw"
        else:
            state = "eligible"
        row["status"] = state
        row["link_count"] = len(related)
    eligible = [r for r in raw if r["status"] == "eligible"]
    quarantine = [r for r in raw if r["status"] != "eligible"]
    write_json(dest / "manifest.json", raw)
    write_json(dest / "eligible.json", eligible)
    write_json(dest / "quarantine.json", quarantine)
    write_json(dest / "links.json", links)
    write_json(dest / "nearest_jpeg.json", nearest)
    old_days = {r["day"] for r in jpeg if r["day"]}
    old_id_days = {(r["horse"], r["day"]) for r in jpeg if r["day"]}
    summary = {"jpeg_sources": len(jpeg), "raw_sources": len(raw),
               "raw_with_preview": sum(bool(r.get("file")) for r in raw),
               "raw_with_exif_date": sum(bool(r["day"]) for r in raw),
               "raw_distinct_bytes": len({r["raw_sha256"] for r in raw}),
               "raw_distinct_previews": len({r["sha256"] for r in raw if r.get("sha256")}),
               "status_counts": dict(Counter(r["status"] for r in raw)),
               "eligible_days": sorted({r["day"] for r in eligible}),
               "eligible_entirely_new_days": sorted({r["day"] for r in eligible} - old_days),
               "eligible_new_identity_days": sorted({(r["horse"], r["day"]) for r in eligible} - old_id_days),
               "eligible_contributing_identities": len({r["horse"] for r in eligible}),
               "cross_label_review_pairs": sum(not x["same_horse"] for x in links),
               "eligible_by_horse": dict(Counter(r["horse"] for r in eligible))}
    write_json(dest / "summary.json", summary)
    print(json.dumps(summary, ensure_ascii=False))


if __name__ == "__main__":
    if sys.argv[1] == "stream":
        stream(Path(sys.argv[2]))
    elif sys.argv[1] == "reconcile":
        reconcile(*map(Path, sys.argv[2:5]))
    else:
        raise SystemExit("expected stream or reconcile")
