"""Generate reproducible sensor previews for independent annotation review."""

from __future__ import annotations

import json
from pathlib import Path

from PIL import Image, ImageDraw

from pallet.data import canonical_records, load_frame, scan_dataset
from pallet.proposals import sensor_visualization


DEFAULT_QUERIES = (
    "2023_6_28/28-06-2023_02-20-01#4",
    "2024_3_27_sort",
    "2024_6_9",
    "2024_10_30",
    "2024_11_27",
    "2024_11_29",
    "2025_3_",
    "2025_7_11",
)


def generate_previews(root, output, *, queries=DEFAULT_QUERIES):
    rows = canonical_records(scan_dataset(root))
    output = Path(output)
    output.mkdir(parents=True, exist_ok=True)
    result = []
    for index, query in enumerate(queries):
        record = next((row for row in rows if query in row.frame_id), None)
        if record is None:
            result.append({"query": query, "error": "no matching frame"})
            continue
        try:
            frame = load_frame(record)
            sensor = sensor_visualization(frame)
            width, height = sensor.size
            canvas = Image.new("RGB", (width * 2, height + 30), (15, 18, 20))
            canvas.paste(sensor, (0, 30))
            if "rgb" in record.paths:
                with Image.open(record.paths["rgb"]) as rgb:
                    canvas.paste(rgb.convert("RGB").resize((width, height)), (width, 30))
            draw = ImageDraw.Draw(canvas)
            draw.text((5, 8), f"{index} sensor (native {width}x{height})", fill="white")
            draw.text((width + 5, 8), "RGB evidence (unregistered)", fill="white")
            path = output / f"{index:02d}.png"
            canvas.save(path)
            result.append({"query": query, "frame_id": record.frame_id,
                           "group_id": record.group_id, "domain": record.domain,
                           "split_reference": "read annotations.jsonl by frame_id",
                           "sensor_width": width, "sensor_height": height,
                           "preview": str(path), "source_paths": {k: str(v) for k, v in record.paths.items()}})
        except Exception as exc:
            result.append({"query": query, "frame_id": record.frame_id,
                           "error": str(exc)})
    (output / "index.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
    return result
