"""Metrics conformance scenarios (CONF-M-* in ``contracts.md`` §10).

Exercise the OPTIONAL :class:`~mgf.vm.core.contracts.MetricsBackend`
Protocol (D-G13). Each scenario is a callable taking a ``MetricsBackend``
instance and either passing (return) or failing (raise).
"""

from __future__ import annotations

from datetime import timedelta
from typing import TYPE_CHECKING

from mgf.vm.core.exceptions import DomainNotFound
from mgf.vm.core.ids import DomainId

if TYPE_CHECKING:
    from mgf.vm.core.contracts import MetricsBackend


def sample_metrics_observation(adapter: MetricsBackend, *, known: DomainId) -> None:
    """CONF-M-01 — sample_metrics returns a UTC-aware MetricsSample (Wave-B).

    A read-only observation on the OPTIONAL :class:`MetricsBackend`: sample a
    known domain and assert the neutral shape — cumulative counters present,
    ``sampled_at`` UTC-aware (DP-12). Sampling is idempotent (two samples of
    the same domain are both valid; sampling does not mutate the domain).
    A sample of an unknown domain raises ``DomainNotFound``.
    """
    sample = adapter.sample_metrics(known)
    assert sample.cpu_time_ns >= 0, "cpu_time_ns is a cumulative counter"
    assert sample.memory_used_bytes >= 0
    assert sample.sampled_at.tzinfo is not None, "sampled_at must be tz-aware (DP-12)"
    assert sample.sampled_at.utcoffset() == timedelta(0), "sampled_at must be UTC"

    # Idempotent: a second sample of the same domain is also valid.
    again = adapter.sample_metrics(known)
    assert again.sampled_at.utcoffset() == timedelta(0)

    # An unknown domain raises DomainNotFound.
    raised = False
    try:
        adapter.sample_metrics(DomainId("conf-m-01-no-such-domain"))
    except DomainNotFound:
        raised = True
    assert raised, "sample_metrics(unknown) must raise DomainNotFound"


__all__ = ["sample_metrics_observation"]
