from __future__ import annotations

import hashlib

import pytest

from shamash_openclaw._setup import _parse_sha256sums, _verify_binary_checksum


def test_parse_sha256sums_supports_space_and_star_formats() -> None:
    checksums = _parse_sha256sums(
        "a" * 64 + "  shamash-linux-x64\n" + "b" * 64 + " *shamash-darwin-arm64\n"
    )
    assert checksums["shamash-linux-x64"] == "a" * 64
    assert checksums["shamash-darwin-arm64"] == "b" * 64


def test_verify_binary_checksum_accepts_matching_digest(tmp_path) -> None:
    binary_path = tmp_path / "shamash-linux-x64"
    payload = b"trusted binary payload"
    binary_path.write_bytes(payload)
    digest = hashlib.sha256(payload).hexdigest()
    _verify_binary_checksum("shamash-linux-x64", binary_path, f"{digest}  shamash-linux-x64\n")


def test_verify_binary_checksum_rejects_missing_entry(tmp_path) -> None:
    binary_path = tmp_path / "shamash-linux-x64"
    binary_path.write_bytes(b"trusted binary payload")
    with pytest.raises(RuntimeError, match="Missing checksum entry"):
        _verify_binary_checksum("shamash-linux-x64", binary_path, "")


def test_verify_binary_checksum_rejects_mismatch(tmp_path) -> None:
    binary_path = tmp_path / "shamash-linux-x64"
    binary_path.write_bytes(b"trusted binary payload")
    with pytest.raises(RuntimeError, match="Checksum mismatch"):
        _verify_binary_checksum("shamash-linux-x64", binary_path, f"{'0' * 64}  shamash-linux-x64\n")
