from __future__ import annotations

from pathlib import Path
import zipfile

import pytest

from scripts.verify_dualcoach_v11_candidate import (
    verify_release_inputs,
    verify_product_binding_delta,
    verify_wheel_delta,
)


RELEASE_ROOT = Path(__file__).parents[2] / "dualcoach" / "releases"
BASE = RELEASE_ROOT / "v1.0.0" / "delivered"
SUCCESSOR = RELEASE_ROOT / "v1.1.0"


def test_successor_wheel_has_only_the_ttl_and_record_delta() -> None:
    delta = verify_wheel_delta(
        BASE / "artifacts" / "hermes_agent-0.17.0-py3-none-any.whl",
        SUCCESSOR / "artifacts" / "hermes_agent-0.17.0-py3-none-any.whl",
    )

    assert delta.member_count == 992
    assert delta.changed_members == (
        "gateway/platforms/telegram_customer_bootstrap.py",
        "hermes_agent-0.17.0.dist-info/RECORD",
    )


def test_successor_binding_changes_only_the_hermes_wheel() -> None:
    candidate = verify_product_binding_delta(
        BASE / "preexecution-product-binding.json",
        SUCCESSOR / "preexecution-product-binding.json",
    )

    assert candidate == (
        "0e383539aea1b83205771772f1e8b417840defe60f5ea6ce184f80e3af8d25f9"
    )


def test_release_inputs_bind_fresh_source_and_installed_golden_paths() -> None:
    result = verify_release_inputs(BASE, SUCCESSOR)

    assert result == {
        "candidate_digest": (
            "0e383539aea1b83205771772f1e8b417840defe60f5ea6ce184f80e3af8d25f9"
        ),
        "installed_golden_path": "ACTUAL_INSTALLED_GOLDEN_PATH_PASS",
        "source_golden_path": "ACTUAL_SOURCE_GOLDEN_PATH_PASS",
        "wheel_member_count": 992,
    }


def test_successor_wheel_rejects_unrecorded_member_tampering(
    tmp_path: Path,
) -> None:
    successor = (
        SUCCESSOR / "artifacts" / "hermes_agent-0.17.0-py3-none-any.whl"
    )
    tampered = tmp_path / successor.name
    with (
        zipfile.ZipFile(successor) as source,
        zipfile.ZipFile(tampered, "w") as target,
    ):
        for info in source.infolist():
            payload = source.read(info.filename)
            if info.filename == "gateway/platforms/telegram.py":
                payload += b"\n"
            target.writestr(info, payload)

    with pytest.raises(ValueError, match="RECORD content binding"):
        verify_wheel_delta(
            BASE / "artifacts" / "hermes_agent-0.17.0-py3-none-any.whl",
            tampered,
        )
