"""Read and write keyframe .meta.json sidecar files."""

__author__ = "Lene Preuss <lene.preuss@gmail.com>"

import json
from pathlib import Path

from stable_delusion.project.models import KeyframeSidecar


class KeyframeSidecarRepository:
    """Reads and writes <image>.meta.json sidecar files."""

    def _sidecar_path(self, image_path: Path) -> Path:
        return image_path.with_suffix(image_path.suffix + ".meta.json")

    def write(self, image_path: Path, sidecar: KeyframeSidecar) -> None:
        sidecar_path = self._sidecar_path(image_path)
        sidecar_path.write_text(json.dumps(sidecar.to_dict(), indent=2), encoding="utf-8")

    def read(self, image_path: Path) -> KeyframeSidecar:
        sidecar_path = self._sidecar_path(image_path)
        if not sidecar_path.exists():
            raise FileNotFoundError(f"Sidecar not found: {sidecar_path}")
        try:
            data = json.loads(sidecar_path.read_text(encoding="utf-8"))
            return KeyframeSidecar.from_dict(data)
        except json.JSONDecodeError as e:
            raise FileNotFoundError(f"Sidecar is malformed: {sidecar_path}") from e

    def list_in_group(self, group_dir: Path) -> list[tuple[Path, KeyframeSidecar]]:
        results = []
        for sidecar_path in group_dir.glob("*.meta.json"):
            image_name = sidecar_path.name[: -len(".meta.json")]
            image_path = group_dir / image_name
            results.append((image_path, self.read(image_path)))
        return sorted(results, key=lambda x: x[1].index)
