import hashlib
import json
from pathlib import Path

import pytest

from hessian_recipes.releases import bundle


def inputs(tmp_path, status="complete"):
    from hessian_recipes.evaluation import run

    card = tmp_path / "card.md"
    card.write_text("# Example adapter\nPrivate experiment. No publication approval.")
    spec = Path(__file__).resolve().parents[1] / "benchmarks/reasoning_reliability/spec.json"
    data = run(spec, tmp_path / "evaluation")
    data["status"] = status
    report = tmp_path / "evaluation/report.json"
    report.write_text(json.dumps(data))
    artifact = tmp_path / "adapter.json"
    artifact.write_text('{"rank": 8}')
    return dict(model_card=card, report=report, artifacts=[artifact])


def test_bundle_content_hashes_and_no_publication(tmp_path):
    kwargs = inputs(tmp_path)
    output = tmp_path / "release"
    result = bundle(output, **kwargs)
    assert not result["published"] and not result["release_eligible"]
    for entry in result["files"]:
        assert hashlib.sha256((output / entry["path"]).read_bytes()).hexdigest() == entry["sha256"]
    assert json.loads((output / "bundle.json").read_text()) == result
    with pytest.raises(ValueError, match="already exists"):
        bundle(output, **kwargs)


def test_bundle_requires_successful_evidence(tmp_path):
    kwargs = inputs(tmp_path, status="failed")
    with pytest.raises(ValueError, match="complete"):
        bundle(tmp_path / "release", **kwargs)
    assert not (tmp_path / "release").exists()


def test_bundle_rejects_duplicate_basenames(tmp_path):
    kwargs = inputs(tmp_path)
    other = tmp_path / "other"
    other.mkdir()
    (other / "adapter.json").write_text("other weights")
    kwargs["artifacts"].append(other / "adapter.json")
    with pytest.raises(ValueError, match="unique"):
        bundle(tmp_path / "release", **kwargs)


def test_bundle_rejects_inconsistent_evidence(tmp_path):
    kwargs = inputs(tmp_path)
    report = kwargs["report"]
    data = json.loads(report.read_text())
    data["metrics"]["correct"] += 1
    report.write_text(json.dumps(data))
    with pytest.raises(ValueError, match="evidence is invalid"):
        bundle(tmp_path / "release", **kwargs)
    assert not (tmp_path / "release").exists()
