"""REC-236: behavioral tests for the SSOT ref-integrity checker (check_paths).

check_paths is the ONE checker shared by the find_broken_refs CLI and the
EpisodeRunner pre-submit preflight. These assert per-ref pass/fail AND the
LFS-aware remediation branch, on REAL files built in tmp_path.
"""
from pathlib import Path

from recoil.pipeline.tools.find_broken_refs import (
    check_paths,
    _LFS_REMEDIATION,
    _BROKEN_REMEDIATION,
)

# PNG 8-byte magic header; pad past the 1024-byte minimum to be a "real" image.
_PNG_MAGIC = b"\x89PNG\r\n\x1a\n"


def _write_valid_png(path: Path) -> Path:
    path.write_bytes(_PNG_MAGIC + b"\x00" * 2048)
    return path


def _write_lfs_pointer(path: Path) -> Path:
    path.write_bytes(
        b"version https://git-lfs.github.com/spec/v1\n"
        b"oid sha256:1111111111111111111111111111111111111111111111111111111111111111\n"
        b"size 12345\n"
    )
    return path


def test_valid_image_no_broken(tmp_path):
    good = _write_valid_png(tmp_path / "good.png")
    assert check_paths([good]) == []


def test_garbage_too_small_is_broken_non_lfs(tmp_path):
    bad = tmp_path / "stub.png"
    bad.write_bytes(b"not an image")  # < 1024 bytes, no magic
    broken = check_paths([bad])
    assert len(broken) == 1
    assert broken[0].path == bad
    assert broken[0].remediation == _BROKEN_REMEDIATION
    assert broken[0].remediation != _LFS_REMEDIATION


def test_lfs_pointer_is_broken_with_lfs_remediation(tmp_path):
    ptr = _write_lfs_pointer(tmp_path / "pooled.png")
    broken = check_paths([ptr])
    assert len(broken) == 1
    assert broken[0].path == ptr
    assert broken[0].remediation == _LFS_REMEDIATION


def test_symlink_to_valid_target_ok(tmp_path):
    target = _write_valid_png(tmp_path / "real.png")
    link = tmp_path / "link.png"
    link.symlink_to(target)
    assert check_paths([link]) == []


def test_symlink_to_broken_target_is_broken(tmp_path):
    target = tmp_path / "real.png"
    target.write_bytes(b"tiny")  # broken target
    link = tmp_path / "link.png"
    link.symlink_to(target)
    broken = check_paths([link])
    assert len(broken) == 1
    assert broken[0].path == link
    assert broken[0].remediation == _BROKEN_REMEDIATION


def test_missing_ref_is_broken(tmp_path):
    missing = tmp_path / "nope.png"
    broken = check_paths([missing])
    assert len(broken) == 1
    assert broken[0].path == missing
    assert "does not exist" in broken[0].reason


def test_mixed_batch_reports_only_broken(tmp_path):
    good = _write_valid_png(tmp_path / "good.png")
    bad = tmp_path / "bad.png"
    bad.write_bytes(b"x")
    broken = check_paths([good, bad])
    assert [b.path for b in broken] == [bad]
