# SPDX-License-Identifier: AGPL-3.0-or-later
"""The decisive-grade oracle cache (performance plan A1).

Acceptance: old-vs-new grading equivalence over the calibration corpus — the
cached and uncached paths must record identical outcomes and classifications
for every calibration case — plus the caching rules themselves: only decisive
grades are cached, and injection, candidate timeouts, and infrastructure
failures never are (the rerun policy re-executes those by design).
"""

from __future__ import annotations

import pytest

from helpers import experiment_authorization

from orchestrator import experiment, oracle, sandbox, spend


def _grade(tree, manifest, *, cache=None, inject=None):
    return oracle.grade_manifest(
        manifest, tree, runner=experiment.hidden_runner, inject=inject, cache=cache
    )


def test_decisive_grades_are_cached_and_reused(tmp_path):
    target = experiment.build_fixed_target(str(tmp_path))
    manifest = experiment.build_hidden_oracle(target)
    tree = experiment._materialise(target.repository, target.commit, str(tmp_path), "good")
    for relative, content in experiment._SOLUTION_FILES.items():
        with open(f"{tree}/{relative}", "w") as handle:
            handle.write(content)

    cache = oracle.GradeCache()
    first = _grade(tree, manifest, cache=cache)
    second = _grade(tree, manifest, cache=cache)
    assert first.outcomes == second.outcomes
    assert cache.misses == 1 and cache.hits == 1
    # The cached grade is decisive (every outcome PASS/FAIL).
    assert set(first.outcomes.values()) <= set(oracle.DECISIVE)
    # A consumer cannot corrupt the cache through the returned grade.
    second.outcomes["hidden-parse"] = "MUTATED"
    third = _grade(tree, manifest, cache=cache)
    assert third.outcomes["hidden-parse"] == first.outcomes["hidden-parse"]
    assert cache.hits == 2


def test_injected_and_non_decisive_grades_are_never_cached(tmp_path):
    target = experiment.build_fixed_target(str(tmp_path))
    manifest = experiment.build_hidden_oracle(target)
    tree = experiment._materialise(target.repository, target.commit, str(tmp_path), "good")
    for relative, content in experiment._SOLUTION_FILES.items():
        with open(f"{tree}/{relative}", "w") as handle:
            handle.write(content)

    cache = oracle.GradeCache()
    inject = {"hidden-parse": oracle.GRADE_INFRASTRUCTURE_ERROR}
    first = _grade(tree, manifest, cache=cache, inject=inject)
    second = _grade(tree, manifest, cache=cache, inject=inject)
    assert first.outcomes == second.outcomes
    assert cache.hits == 0 and cache.misses == 0

    # A grade holding a non-decisive outcome is refused by the cache even if
    # offered: CANDIDATE_TIMEOUT is re-executed by the rerun policy.
    timeout_grade = oracle.OracleGrade(
        oracle_version=manifest.oracle_version,
        outcomes={**first.outcomes, "hidden-parse": oracle.GRADE_CANDIDATE_TIMEOUT},
    )
    cache.put(("any", "any"), timeout_grade)
    assert cache.get(("any", "any")) is None


@pytest.mark.slow
@pytest.mark.timeout(600)
def test_cached_and_uncached_calibration_agree_over_the_corpus(tmp_path):
    """Old-vs-new equivalence over the calibration corpus: the five cases
    classify and record identically whether or not the cache is in play."""
    caps = sandbox.capabilities()
    if not caps.profile_available:
        pytest.fail(f"NAMESPACE_V1 unavailable (fail-closed gate): {caps.unavailable_reason()}")
    target = experiment.build_fixed_target(str(tmp_path))
    manifest = experiment.build_hidden_oracle(target)

    uncached = experiment.calibrate_oracle(target, manifest, str(tmp_path / "plain"))
    cache = oracle.GradeCache()
    cached = experiment.calibrate_oracle(
        target, manifest, str(tmp_path / "cached"), grade_cache=cache
    )

    assert [c.case_id for c in uncached.cases] == [c.case_id for c in cached.cases]
    for plain_case, cached_case in zip(uncached.cases, cached.cases):
        assert plain_case.classification == cached_case.classification, plain_case.case_id
        assert plain_case.outcomes == cached_case.outcomes, plain_case.case_id

    # Re-running the corpus with the same cache is where the reuse shows:
    # decisive case trees are graded once, calibration devices still twice.
    again = experiment.calibrate_oracle(
        target, manifest, str(tmp_path / "again"), grade_cache=cache
    )
    assert [c.classification for c in again.cases] == [
        c.classification for c in uncached.cases
    ]
    assert cache.hits >= 1
