"""REC-238: the regenerate route patches the rejected segment's replaced_by
provenance under the v3 ``renders/ep_NNN`` dir, not the deprecated
``output/video`` dir (which is empty/absent on v3 projects, so replaced_by was
silently never written).
"""

import json

import pytest

from recoil.core.exceptions import SidecarCorruptError
from recoil.core.paths import ProjectPaths
from recoil.workspace import server

ORIG = "EP001_SH02_000_abc"
NEW = "EP001_SH02_001_def"


@pytest.fixture
def project(tmp_path, monkeypatch):
    monkeypatch.setattr(
        ProjectPaths, "for_project", classmethod(lambda cls, p: cls.from_root(tmp_path))
    )
    return tmp_path


def _seg_under(ep_dir):
    ep_dir.mkdir(parents=True, exist_ok=True)
    mp4 = ep_dir / "shot_02_FROM_PASS_000_xyz_take1.mp4"
    mp4.write_bytes(b"\x00")
    return mp4


def test_replaced_by_written_under_renders(project):
    ep = ProjectPaths.from_root(project).episode_renders_dir(1)
    mp4 = _seg_under(ep)
    (ep / f"{mp4.name}.json").write_text(json.dumps({"status": "rejected"}))

    server._patch_segment_replaced_by("tartarus", 1, "02", ORIG, NEW)

    sc = json.loads((ep / f"{mp4.name}.json").read_text())
    assert sc["replaced_by"] == NEW


def test_segment_under_deprecated_output_video_is_not_scanned(project):
    # Counterexample to the old behavior: a segment under output/video is NOT
    # touched now that the scan targets renders/.
    old = project / "output" / "video" / "ep_001"
    mp4 = _seg_under(old)
    (old / f"{mp4.name}.json").write_text(json.dumps({"status": "rejected"}))

    server._patch_segment_replaced_by("tartarus", 1, "02", ORIG, NEW)

    sc = json.loads((old / f"{mp4.name}.json").read_text())
    assert "replaced_by" not in sc


def test_corrupt_sidecar_raises(project):
    ep = ProjectPaths.from_root(project).episode_renders_dir(1)
    mp4 = _seg_under(ep)
    (ep / f"{mp4.name}.json").write_text("{corrupt")
    with pytest.raises(SidecarCorruptError):
        server._patch_segment_replaced_by("tartarus", 1, "02", ORIG, NEW)
