"""02 — claim a resource under a context-managed Lease, get the raw channel,
release. The lease is bound to the connection's liveness (G3): if THIS
script crashes mid-block, the broker reclaims the lease and safe-resets
the device. No recovery code required on the caller side.

Companion recipe: ../recipes/claim-a-device-for-vfio-passthrough.md
"""

from __future__ import annotations

import sys

from mgf.hrb import ClaimMode, Client, ConflictError, MgfHrbError


SOCKET = "/tmp/mgf-hrb.sock"
# Use whatever the broker's seeded devices report; the skeleton broker
# (hrb-code/src/server.zig) seeds two PCI devices.
TARGET_URN = "hw:/pci/0000:01:00.0/fn0"


def main() -> int:
    try:
        with Client.connect(SOCKET) as client:
            # Context-managed claim — releases on scope exit, even on exception.
            # `deadline_ms` is the survivability-contract budget (D-029):
            # acquire MUST complete, error, or be abandonable within 5 s.
            with client.claim(TARGET_URN, ClaimMode.EXCLUSIVE, deadline_ms=5_000) as lease:
                print(f"Claimed {TARGET_URN} as lease #{lease.lease_id}.")

                # G4: get the raw channel and act on the device directly.
                # The broker is absent from the use path; once we hold the
                # raw handle, our access is broker-independent.
                raw = lease.raw(deadline_ms=1_000)
                print(f"Raw channel granted: {raw}")

                # ... your domain work goes here ...

            print("Released. Device is safe-reset and re-claimable.")
            return 0

    except FileNotFoundError:
        print(f"No broker is listening at {SOCKET}.", file=sys.stderr)
        return 2
    except ConflictError:
        print(
            f"{TARGET_URN} is already exclusively held by another tenant. "
            "The lease lattice (Part 3.3) refused the second claim — exactly as designed.",
            file=sys.stderr,
        )
        return 1
    except MgfHrbError as exc:
        print(f"Broker error: {exc}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
