#!/usr/bin/env python3
"""D29 contracts: no lease is a no-op success; half-provisioned still fails closed."""

from __future__ import annotations

import importlib.util
import unittest
from pathlib import Path

TOOLS = Path(__file__).parents[2] / "framework/tools/lease-broker"
REVOKE_PATH = TOOLS / "revoke-lease.py"

_spec = importlib.util.spec_from_file_location("revoke_lease", REVOKE_PATH)
assert _spec and _spec.loader
revoke_lease = importlib.util.module_from_spec(_spec)
import sys as _sys

_sys.path.insert(0, str(TOOLS))
_spec.loader.exec_module(revoke_lease)

ARGV = ["--runtime", "claude", "--reason", "pre-compact"]
VALID_SESSION = "a" * 64


def _explode(*_args, **_kwargs):
    raise AssertionError("broker must not be contacted when no lease is held")


class RevokeWithoutLease(unittest.TestCase):
    def test_no_lease_variables_is_a_noop_success(self) -> None:
        """The D29 case: bare-launched session, nothing to revoke, must not deny."""
        self.assertEqual(
            revoke_lease.main(ARGV, environ={}, request=_explode),
            0,
        )

    def test_no_lease_does_not_contact_the_broker(self) -> None:
        """A no-op must be vacuous: no socket, no generation bump, no transport."""
        revoke_lease.main(ARGV, environ={"HOME": "/nonexistent"}, request=_explode)

    def test_socket_without_session_still_fails_closed(self) -> None:
        """Half-provisioned is misconfiguration, not absence. Fail-closed stands."""
        self.assertEqual(
            revoke_lease.main(
                ARGV,
                environ={"MOSAIC_LEASE_BROKER_SOCKET": "/tmp/nonexistent.sock"},
                request=_explode,
            ),
            2,
        )

    def test_session_without_socket_still_fails_closed(self) -> None:
        """The mirror case, so the guard cannot be satisfied by either half alone."""
        self.assertEqual(
            revoke_lease.main(
                ARGV,
                environ={"MOSAIC_LEASE_SESSION_ID": VALID_SESSION},
                request=_explode,
            ),
            2,
        )

    def test_empty_string_counts_as_absent(self) -> None:
        """An exported-but-empty variable is not a lease."""
        self.assertEqual(
            revoke_lease.main(
                ARGV,
                environ={
                    "MOSAIC_LEASE_BROKER_SOCKET": "",
                    "MOSAIC_LEASE_SESSION_ID": "",
                },
                request=_explode,
            ),
            0,
        )


if __name__ == "__main__":
    unittest.main()
