# SPDX-License-Identifier: AGPL-3.0-or-later
"""Session-scoped shared fixtures (performance plan A3).

The experiment pipeline's prefix — the fixed target, the hidden oracle
manifest, the five-case oracle calibration, and the four unmeasured pilots —
is deterministic under the scripted model and immutable once built, yet it was
rebuilt per test module (the single most expensive setup in the suite). These
fixtures build it **once per pytest session**, lazily (only when a test asks),
and share it read-only. Trials are never shared: every module that runs a
comparison still owns its workdir, its spend ledger, and its trial stores.

Fixtures only: no classes and no ``test_bug_*`` functions live here, so the
fixture-fidelity and open-defect registry AST scans
(``tests/test_fixture_fidelity.py``, ``tests/test_open_defect_registry.py``)
are unaffected by this file.
"""

from __future__ import annotations

import dataclasses

import pytest

from helpers import experiment_authorization

from orchestrator import experiment, sandbox


@dataclasses.dataclass(frozen=True)
class ExperimentPrefix:
    """The immutable, shared prefix of a frozen experiment run."""

    workdir: str
    target: object
    oracle: object
    calibration: object
    pilots: object
    spend_ledger: object
    gate_passed: bool
    gate_failures: tuple


@pytest.fixture(scope="session")
def experiment_prefix(tmp_path_factory) -> ExperimentPrefix:
    """Build the expensive experiment prefix once per session.

    Fails closed exactly as the paid entry points do: without the NAMESPACE_V1
    profile every hidden grade would be an oracle infrastructure failure.
    """
    capabilities = sandbox.capabilities(refresh=True)
    if not capabilities.profile_available:
        pytest.fail(
            f"NAMESPACE_V1 unavailable (fail-closed gate): "
            f"{capabilities.unavailable_reason()}"
        )
    from orchestrator import conformance, spend

    workdir = str(tmp_path_factory.mktemp("shared-experiment-prefix"))
    gate_report = conformance.run_full_suite()
    target = experiment.build_fixed_target(workdir)
    oracle_manifest = experiment.build_hidden_oracle(target)
    calibration = experiment.calibrate_oracle(target, oracle_manifest, workdir)
    ledger = spend.open_spend_ledger(workdir, experiment_authorization())
    pilots = experiment.run_pilots(
        target, oracle_manifest, workdir, spend_ledger=ledger
    )
    return ExperimentPrefix(
        workdir=workdir,
        target=target,
        oracle=oracle_manifest,
        calibration=calibration,
        pilots=pilots,
        spend_ledger=ledger,
        gate_passed=gate_report.passed,
        gate_failures=tuple(gate_report.failures()),
    )
