"""mgf.hrb — the Magogi Foundation hardware-resource-broker Python SDK.

The no-FFI client surface for the broker (Part 8 of the design). This package
talks to the broker as bytes-on-a-socket; it links zero Zig, owns no
cross-language memory, and surfaces typed broker-side outcomes as typed
Python exceptions (EH-01 / EH-02).

The public API — everything a consumer should import — is enumerated below
in ``__all__``. Anything not in this list is private to the package and may
change between minors (AP-10 / AP-14).

The Zig kernel-seam half of the broker lives in ``hrb-code/`` at the
project root; that side is not importable from here by design (the SOCKET
is the boundary, not a Python ↔ Zig FFI seam — D-005).

For the architectural backstory: read ``INDEX.md`` then
``hrb-design/mgf-hrb-complete-design.md`` Part 8.
"""

from __future__ import annotations

from mgf.hrb._client import Client, Lease
from mgf.hrb._shm import ShmChannel
from mgf.hrb.config import HrbSettings
from mgf.hrb.diagnostics import Category as DoctorCategory
from mgf.hrb.diagnostics import DoctorFinding
from mgf.hrb.diagnostics import Severity as DoctorSeverity
from mgf.hrb.domain import (
    AuditOutcomeSummary,
    AuditRecord,
    AuditTailResult,
    BackendCapability,
    ChainEntry,
    ClaimMode,
    ControlOutcome,
    ControlVerb,
    DriverInfo,
    DumpAllResult,
    DumpChainResult,
    Family,
    FieldFidelity,
    IdentityClass,
    InspectFullResult,
    InspectNode,
    InspectTree,
    Kind,
    LeaseRecord,
    Resource,
    ResourceDetail,
    StateSnapshot,
    Subscription,
    SupersededBy,
    WorkerSnapshot,
)
from mgf.hrb.exceptions import (
    BadRequestError,
    ConflictError,
    HardwareFaultError,
    InvalidTokenError,
    MgfHrbError,
    NotFoundError,
    NotPermittedError,
    OverloadedError,
    RevokedError,
    TimeoutError,
    UnavailableError,
    UnsupportedError,
)
from mgf.hrb.identity import (
    ComparatorOpts,
    Confidence,
    Contribution,
    ScoreResult,
    Snapshot,
    same_likely,
    same_likely_explained,
)
from mgf.hrb.predicates import (
    EVENT_KINDS,
    PREDICATE_GRAMMAR_VERSION,
    all_of,
    any_of,
    attr_eq,
    attr_in,
    kind_in,
    not_,
    urn_glob,
)
from mgf.hrb.sysfs import snapshot_from_sysfs

# Module-shadowing guard. If a rogue wheel named `mgf.hrb.fmt` is
# installed via PyPI typo-squat or sys.path injection, our PR-06
# fence (stdlib-only) and PR-06 dog-food invariants would be
# silently subverted. Verify at import time that the loaded fmt
# module is the SDK's own — fails loud rather than serving an
# attacker's substitute.
_pkg_dir = __import__("os").path.dirname(__file__)
from mgf.hrb import fmt as _fmt  # noqa: E402

if not _fmt.__file__ or not _fmt.__file__.startswith(_pkg_dir):
    raise ImportError(
        f"mgf.hrb.fmt was loaded from {_fmt.__file__!r}, not from the "
        f"installed SDK at {_pkg_dir!r}. A rogue package may be shadowing "
        "the SDK module. Refuse to continue.",
    )
del _pkg_dir, _fmt

__version__ = "0.1.11"

__all__ = [
    # the closed set of event-kind tags `kind_in(...)` accepts —
    # mirrors the broker's `subscription.EventKind` (M-B B3)
    "EVENT_KINDS",
    # the predicate-grammar version the builders below emit; compare
    # against `Client.predicate_grammar_version()` (what the broker
    # parses) before sending a non-trivial tree (M-B B3)
    "PREDICATE_GRAMMAR_VERSION",
    # one record from `Client.audit_tail()` (Part 13 §5.6.1) —
    # typed return shape for AuditTailResult.outcome_summary() —
    # (ok, err, other, newest_error) tally; replaces the inline loop
    # the CLI's _doctor.py used to do (A2 / presentation-layer plan)
    "AuditOutcomeSummary",
    # one row per wire op the broker handled, with timing +
    # outcome + optional URN / err / correlation_id
    "AuditRecord",
    # one record per `Client.audit_tail()` call (Part 13 §5.6.4)
    "AuditTailResult",
    # typed worker-introspection row (FEEDBACK SDK-05 — the typed
    # projection over `Client.capabilities()`'s wire dict)
    "BackendCapability",
    "BadRequestError",
    # one rung of `Client.dump_chain()` (Part 13 §5.5.2 — leaf-
    # first parent-chain walk; carries the rung's urn, topology
    # level tag, and a short human summary)
    "ChainEntry",
    # domain types
    "ClaimMode",
    # entry point
    "Client",
    "ComparatorOpts",
    # identity comparator (FEEDBACK MODEL-01; Python mirror of identity.zig)
    "Confidence",
    "ConflictError",
    "Contribution",
    # one record per `Client.control()` call (Part 13 §5.1.2 —
    # the optimistic-concurrency disclosure: generation,
    # applied_value, queue_depth, superseded_by)
    "ControlOutcome",
    "ControlVerb",
    # doctor diagnostics surface (FEEDBACK TOOLS-02 — shared engine for
    # the `mgf-hrb doctor` CLI and the programmatic `Client.doctor()`
    # call so GUIs and the CLI report identical findings)
    "DoctorCategory",
    "DoctorFinding",
    "DoctorSeverity",
    # one record per `Client.driver_info()` call (Part 13 §5.2.2 —
    # broker-visible driver interface: load state, bound count,
    # registry-derived fields; the registry half ships in 3B)
    "DriverInfo",
    # one record per `Client.dump_all()` call (Part 13 §5.5.3 — the
    # bulk-introspection surface; ordered list of ResourceDetail
    # plus an honest `truncated` flag)
    "DumpAllResult",
    # one record per `Client.dump_chain()` call (Part 13 §5.5.2 —
    # parent-chain topology trace; ordered tuple of ChainEntry plus
    # `fidelity`, `captured_at_ms`, and an honest `truncated` flag)
    "DumpChainResult",
    "Family",
    "FieldFidelity",
    "HardwareFaultError",
    # typed config (CF-01)
    "HrbSettings",
    "IdentityClass",
    # one record per `Client.inspect_full()` call (Part 13 §5.5.1 —
    # the per-URN tree-walk surface; nested sysfs subtree plus an
    # honest `truncated` flag and broker-side `captured_at_ms`)
    "InspectFullResult",
    "InspectNode",
    "InspectTree",
    "InvalidTokenError",
    "Kind",
    # the lease handle returned by `Client.claim` (SDK-04 — typed
    # so consumers can annotate "I hold a Lease" without violating
    # AP-14 by reaching into `mgf.hrb._client`)
    "Lease",
    # one row per live lease returned by `Client.list_leases`
    # (FEEDBACK SDK-03 — the multi-operator "who holds what" view)
    "LeaseRecord",
    # exception hierarchy (EH-01)
    "MgfHrbError",
    "NotFoundError",
    "NotPermittedError",
    "OverloadedError",
    "Resource",
    # one row per `Client.inspect()` call (FEEDBACK SDK-02 typed half
    # — the consumer-facing typed projection over the wire dict)
    "ResourceDetail",
    "RevokedError",
    "ScoreResult",
    # the client side of the Part 5.3 shared-memory data plane,
    # returned by `Client.open_shm_channel`
    "ShmChannel",
    "Snapshot",
    # broker-wide self-state snapshot returned by
    # `Client.state_snapshot()` (Part 13 §5.6.2)
    "StateSnapshot",
    # one record per `Client.subscribe()` call (Part 13 §5.4.2 —
    # registers a server-side event filter; the typed handle carries
    # the broker-assigned subscription id + queue cap)
    "Subscription",
    # the `superseded_by` payload on a `ControlOutcome` (Part 13
    # §5.1.2 — non-null when another writer raced ahead before
    # our response returned)
    "SupersededBy",
    "TimeoutError",
    "UnavailableError",
    "UnsupportedError",
    # one per-worker entry in a StateSnapshot's `workers` map
    "WorkerSnapshot",
    "__version__",
    # typed predicate builders for `Client.subscribe(predicate=...)`
    # (M-B B3 — the v1 grammar, so consumers never hand-write the AST;
    # every one refuses the broker's own N2 empty-array law up front)
    "all_of",
    "any_of",
    "attr_eq",
    "attr_in",
    "kind_in",
    "not_",
    "same_likely",
    "same_likely_explained",
    # I/O helper for `Snapshot` — reads sysfs USB-device attrs.
    # Bridges the gap until USB-02's worker ships and
    # Client.inspect() can populate the same fields (SDK-07).
    "snapshot_from_sysfs",
    "urn_glob",
]
