import json
from pathlib import Path

from recoil.pipeline.core.persistence import save_scene
from recoil.pipeline.core.take import Beat, Scene


def _json_body(response) -> dict:
    return json.loads(response.body.decode("utf-8"))


def _write_scene(
    path: Path,
    batch_id: str,
    batch_shots: list[dict],
    board_artifact: str | None = None,
    board_status: str | None = None,
) -> None:
    beat = Beat(
        beat_id=batch_id,
        beat_metadata={
            "batch_shots": batch_shots,
            "shared_location_id": f"loc_{batch_id.lower()}",
            "shared_characters": ["ada", "ben"],
            "total_duration_s": sum(shot["duration_s"] for shot in batch_shots),
        },
    )
    if board_artifact is not None:
        # REC-231 Phase 4: the wall dereferences the active body's pointed board
        # (beat.board.artifact) instead of globbing the newest sidecar on disk, so a
        # scene only shows a board when its first beat carries a board pointer.
        beat.set_board_proposed(
            artifact=board_artifact, source_sha256="0" * 64, fingerprint_version=1
        )
        if board_status == "approved":
            beat.approve_board("JT")
    save_scene(Scene(scene_id=batch_id, beats=[beat]), path)


def _write_sidecar(path: Path, data: dict) -> None:
    path.write_text(json.dumps(data), encoding="utf-8")
