# SPDX-License-Identifier: AGPL-3.0-or-later
"""Reviewer probe for the carried finding F1 (phase4-recursive-planning-integration-provider).

These shapes were red at the reviewed revision, as the finding's evidence. The
continuation fixes step fixes F1, so they now pass and are maintained as pins of
the enforced property: the depth walk is parentward and ``MAX_PROPOSAL_DEPTH`` /
``maximum_depth`` bind in production. They are not ``test_bug_*`` and are not
registered in tests/open_defects.yaml; the probe was absorbed as maintained pins
of a fixed defect, which discharges the earlier registration note.

F1: ``Controller.node_depth`` walks CHILD_OF in the wrong direction. Production
writes CHILD_OF with ``from_node_id=child, to_node_id=parent``
(``Controller.propose_decomposition``'s RELATION_RECORDED), and the reducer's
``children_of`` reads ``to_node_id`` as the parent. ``_node_depth`` now filters
``from_node_id == current`` and steps to ``to_node_id``, walking parentward so a
node's depth is its distance below the run root.
"""
from __future__ import annotations

from typing import Any, Dict, List

import pytest

from helpers import build_run_config

from orchestrator import planning_pilot
from orchestrator.controller import Controller, RunLimitExhausted
from orchestrator.executor import ScriptedExecutor
from orchestrator.store import EventStore

pytestmark = pytest.mark.slow

_ROOT_CRITERION = "ROOT-AC"
_A_CRITERION = "A-AC"
_A1_CRITERION = "A1-AC"


def _child(
    node_id: str,
    scope: str,
    budget_id: str,
    allocation: float,
    criterion_ids: List[str],
    own_criterion: str,
) -> Dict[str, Any]:
    """A production-shaped child: ``criterion_ids`` reference the parent's
    declared criteria, the contract declares the child's own."""
    return {
        "node_id": node_id,
        "mandatory": True,
        "criterion_ids": list(criterion_ids),
        "budget_allocation": {"MODEL_COST": allocation},
        "contract": {
            "description": node_id,
            "owned_scope": [scope],
            "acceptance_criteria": [{"id": own_criterion, "mandatory": True}],
            "budget_id": budget_id,
        },
    }


def _coverage(criterion_id: str, child_id: str) -> Dict[str, Any]:
    return {
        "criterion_id": criterion_id,
        "child_id": child_id,
        "mandatory_cover": True,
    }


def _run(tmp_path, run_id: str, maximum_depth: int):
    store = EventStore(str(tmp_path / f"{run_id}.db"))
    controller = Controller(store, ScriptedExecutor({}))
    config = build_run_config(
        run_id,
        limits={"nodes": 10, "actions": 10, "maximum_depth": maximum_depth},
        root_contract={
            "description": "probe run",
            "owned_scope": ["src/health/**"],
            "acceptance_command": "pytest tests/health",
            "acceptance_criteria": [{"id": _ROOT_CRITERION, "mandatory": True}],
        },
    )
    return store, controller, controller.submit_run(config)


def _two_level_chain(tmp_path, run_id: str, maximum_depth: int):
    """A real run admitted through the production path: root -> a -> a1.

    Uses the controller's own ``admit_derived_decomposition`` twice, so the CHILD_OF
    relations are written exactly as production writes them, and every bound
    except the depth-bounded ones (accuracy of the depth read) holds.
    """
    store, controller, root = _run(tmp_path, run_id, maximum_depth)
    controller.admit_derived_decomposition(
        run_id,
        root,
        "d-root",
        [
            _child(
                f"{run_id}-a",
                "src/health/a/**",
                f"{run_id}-a-budget",
                5.0,
                [_ROOT_CRITERION],
                _A_CRITERION,
            )
        ],
        [_coverage(_ROOT_CRITERION, f"{run_id}-a")],
    )
    controller.admit_derived_decomposition(
        run_id,
        f"{run_id}-a",
        "d-a",
        [
            _child(
                f"{run_id}-a1",
                "src/health/a/a1/**",
                f"{run_id}-a1-budget",
                4.0,
                [_A_CRITERION],
                _A1_CRITERION,
            )
        ],
        [_coverage(_A_CRITERION, f"{run_id}-a1")],
    )
    return store, controller, root


def test_the_root_reads_depth_zero_and_a_true_depth_two_leaf_reads_two_and_subtree_height_is_not_depth(tmp_path):
    run_id = "DEPTH-READ"
    store, controller, root = _two_level_chain(tmp_path, run_id, maximum_depth=3)
    try:
        state = store.state(run_id)
        # The truth: the root is at depth 0 and its grandchild at depth 2.
        assert Controller.node_depth(state, root) == 0
        assert Controller.node_depth(state, f"{run_id}-a1") == 2
    finally:
        store.close()


def test_the_pilot_depth_guard_refuses_a_proposal_at_a_true_depth_two_node_at_bounds(tmp_path):
    run_id = "DEPTH-BOUNDS"
    store, controller, _root = _two_level_chain(tmp_path, run_id, maximum_depth=2)
    try:
        state = store.state(run_id)
        # A proposal made at the depth-2 grandchild is past MAX_PROPOSAL_DEPTH,
        # so the guard must refuse: payload None, record refusing at BOUNDS.
        payload, record, _capability = planning_pilot.propose_decomposition(
            state,
            f"{run_id}-a1",
            lambda _state, parent_node_id: [
                _child(
                    f"{parent_node_id}-grandchild",
                    "src/health/a/a1/grandchild/**",
                    f"{parent_node_id}-grandchild-budget",
                    1.0,
                    [_A1_CRITERION],
                    "GRANDCHILD-AC",
                )
            ],
            proposal_id="p-grandchild",
        )
        assert payload is None
        assert record["admitted"] is False
        assert record["refusing_stage"] == "BOUNDS"
        assert record["accepted_children"] == 0
    finally:
        store.close()


def test_maximum_depth_run_limit_refuses_decomposition_past_the_limit(tmp_path):
    run_id = "DEPTH-LIMIT"
    store, controller, root = _run(tmp_path, run_id, maximum_depth=1)
    try:
        # maximum_depth=1 permits exactly one level below the root. The first
        # decomposition is legal; a node at true depth 1 offering grandchildren
        # exceeds the frozen limit and must refuse honestly.
        controller.admit_derived_decomposition(
            run_id,
            root,
            "d-root",
            [
                _child(
                    f"{run_id}-a",
                    "src/health/a/**",
                    f"{run_id}-a-budget",
                    5.0,
                    [_ROOT_CRITERION],
                    _A_CRITERION,
                )
            ],
            [_coverage(_ROOT_CRITERION, f"{run_id}-a")],
        )
        with pytest.raises(RunLimitExhausted):
            controller.admit_derived_decomposition(
                run_id,
                f"{run_id}-a",
                "d-a",
                [
                    _child(
                        f"{run_id}-a1",
                        "src/health/a/a1/**",
                        f"{run_id}-a1-budget",
                        4.0,
                        [_A_CRITERION],
                        _A1_CRITERION,
                    )
                ],
                [_coverage(_A_CRITERION, f"{run_id}-a1")],
            )
    finally:
        store.close()
