# SPDX-License-Identifier: AGPL-3.0-or-later
"""The phase5-run-entry-fixes-4 review's committed probes (J-class).

F33's artefact retention reading, attacked and pinned across its every face —
the four follow-on event types retained (the CONTEXT's breadth claim), the
owner-payload branch's admission inaccessibility, and the F33 residual (a
crafted terminal-owned id with no prior admission) — plus F30's settle-twice
shape on the accepted lineage, and F34: the run-entry loader's documented
fail-closed claim does not hold for a YAML-unparseable spec file (red at
FINAL; the next step absorbs it green).
"""

import os
import subprocess

import pytest

from orchestrator import events, reducer, run_entry
from orchestrator.events import AdmissionError
from orchestrator.store import EventStore

pytestmark = pytest.mark.slow

_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

_GIT_ENV = {
    "GIT_AUTHOR_NAME": "operator",
    "GIT_AUTHOR_EMAIL": "operator@localhost",
    "GIT_COMMITTER_NAME": "operator",
    "GIT_COMMITTER_EMAIL": "operator@localhost",
}


def _make_repo(root):
    """Idempotent version of tests/test_run_entry.py's helper."""
    repo = os.path.join(root, "target-repo")
    os.makedirs(os.path.join(repo, "src"), exist_ok=True)
    with open(os.path.join(repo, "src", "app.py"), "w") as handle:
        handle.write("def value():\n    raise NotImplementedError('value')\n")
    existing = subprocess.run(
        ["git", "-C", repo, "rev-parse", "HEAD"], capture_output=True, text=True
    )
    if existing.returncode == 0:
        return repo, existing.stdout.strip()
    for args in (["init", "-q"], ["add", "-A"], ["commit", "-q", "-m", "base"]):
        subprocess.run(
            ["git", "-C", repo, *args], env={**os.environ, **_GIT_ENV},
            check=True, capture_output=True,
        )
    commit = subprocess.run(
        ["git", "-C", repo, "rev-parse", "HEAD"], capture_output=True, text=True,
        check=True,
    ).stdout.strip()
    return repo, commit


def _raw_spec(repo, commit, run_id, command, **overrides):
    document = {
        "run_id": run_id,
        "repository": repo,
        "base_commit": commit,
        "snapshot_id": f"TARGET-{run_id}",
        "task_statement": "Make the visible check pass.",
        "project_kernel": {"kernel_id": f"KERNEL-{run_id}"},
        "visible_commands": [command],
        "components": [["core", "src/app.py"]],
        "owned_scope": ["src/**"],
        "acceptance_criteria": ["AC-CORE"],
        "budgets": {"MODEL_COST": 10.0},
        "limits": {"actions": 4, "wall_clock_seconds": 60},
        "policy_version": 1,
        "evidence_policy": {"level": "MEDIUM", "version": 1},
        "executor_profile": "command-executor-v1",
    }
    document.update(overrides)
    return run_entry.validate_run_spec(document)


def _race_log(tmp_path, run_id="RUN-RACE-LOG"):
    """A committed race-order log: the second connection's stop lands while the
    launcher's execution is live; the launcher's stale admissions follow. The
    delivered stale-admission shape (the cancellation races a live lifecycle)."""
    repo, commit = _make_repo(str(tmp_path))
    dimension, amount = "MODEL_COST", 10.0
    spec = _raw_spec(repo, commit, run_id, "true")
    store_path = os.path.join(str(tmp_path), "race.db")
    store = EventStore(store_path)
    try:
        controller, _target, run_id, root = run_entry.build_run(
            spec, store=store, workdir=str(tmp_path)
        )
        attempt_id = controller.plan_attempt(
            run_id, root, {"amount": amount, "dimension": dimension}
        )
        controller._emit(
            run_id, "ACTION_DISPATCHED",
            {"attempt_id": attempt_id, "executor": "command-executor-v1"},
            f"dispatch-{attempt_id}",
        )
        second = EventStore(store_path)
        try:
            run_entry.stop_run(second, run_id)
        finally:
            second.close()
        controller._emit(
            run_id, "DISPATCH_ACKNOWLEDGED",
            {"attempt_id": attempt_id, "token": "token-race"},
            f"ack-{attempt_id}", source="executor",
        )
        artefact_id = f"{attempt_id}-artefact"
        controller._emit(
            run_id, "ARTEFACT_ADMITTED",
            {"artefact_id": artefact_id, "type": "GIT_CANDIDATE",
             "hash": "sha256:c", "attempt_id": attempt_id},
            f"artefact-{attempt_id}",
        )
        controller._emit(
            run_id, "ARTEFACT_INTEGRATED",
            {"artefact_id": artefact_id, "merge_info": {"reference": "r1"}},
            f"integrate-{attempt_id}",
        )
    finally:
        store.close()
    fresh_store = EventStore(store_path)
    try:
        fresh = fresh_store.replay_fresh(run_id)
    finally:
        fresh_store.close()
    return run_id, attempt_id, fresh


def test_review_f33_breadth_all_artefact_follow_ons_retained(tmp_path):
    """The CONTEXT's breadth claim: every artefact-machine follow-on of a
    retained admission is itself late — not only ARTEFACT_INTEGRATED's."""
    follow_ons = {
        "ARTEFACT_VALIDATED": {"validator": "fixture"},
        "ARTEFACT_REJECTED": {"reason": "REJECTED"},
        "ARTEFACT_SUPERSEDED": {"replacement_artefact_id": "other-artefact-x"},
        "ARTEFACT_PUBLISHED": {"publisher": "controller"},
    }
    for event_type, extra in follow_ons.items():
        _run_id, attempt_id, fresh = _race_log(tmp_path / event_type.lower())
        event = events.make_event(
            event_type,
            {"artefact_id": f"{attempt_id}-artefact", **extra},
            idempotency_key=f"probe-{event_type}", schema_version=1,
            policy_version=1, source="controller",
        )
        new_state, effects = reducer.reduce(fresh, event)
        assert [effect.kind for effect in effects] == ["late_event_retained"], event_type
        assert f"{attempt_id}-artefact" not in new_state.artefacts, (
            "F33: the retained admission's candidate must never advance to "
            f"{event_type}'s target"
        )


def test_review_f33_owner_payload_branch_is_admission_inaccessible(tmp_path):
    """The owner's payload branch (`attempt_id` in the follow-on's payload) is
    unreachable through any store surface: the follow-on EventSpecs carry no
    such field and admission rejects extras. Direct reduce faces: a payload
    attempt_id naming a terminal attempt retains; one naming a live attempt
    fails closed."""
    _run_id, attempt_id, fresh = _race_log(tmp_path)
    # (i) no store admission can persist a follow-on payload carrying
    # attempt_id: the EventSpecs' allowed fields reject it.
    crafted = events.make_event(
        "ARTEFACT_INTEGRATED",
        {"artefact_id": "UNSEEN-artefact", "merge_info": {},
         "attempt_id": attempt_id},
        idempotency_key="probe-crafted-extra-field", schema_version=1,
        policy_version=1, source="controller",
    )
    store = EventStore(os.path.join(str(tmp_path), "admit.db"))
    try:
        with pytest.raises(AdmissionError):
            store.admit("UNSEEN", crafted)
    finally:
        store.close()
    # (ii) via pure reduce the payload branch names the terminal attempt:
    # retained.
    carried = events.make_event(
        "ARTEFACT_INTEGRATED",
        {"artefact_id": "UNSEEN2-artefact", "merge_info": {},
         "attempt_id": attempt_id},
        idempotency_key="probe-terminal-carried", schema_version=1,
        policy_version=1, source="controller",
    )
    new_state, effects = reducer.reduce(fresh, carried)
    assert [effect.kind for effect in effects] == ["late_event_retained"]
    # (iii) the payload branch naming a live attempt fails closed.
    planned, _ = reducer.reduce(
        fresh, events.make_event(
            "ATTEMPT_PLANNED",
            {"attempt_id": "RIVET-attempt", "node_id": "RUN-RACE-LOG-root",
             "cause": "INITIAL"},
            idempotency_key="probe-plan-rivet", schema_version=1,
            policy_version=1, source="controller",
        )
    )
    foreign = events.make_event(
        "ARTEFACT_INTEGRATED",
        {"artefact_id": "RIVET-attempt-artefact", "merge_info": {},
         "attempt_id": "RIVET-attempt"},
        idempotency_key="probe-rivet-followon", schema_version=1,
        policy_version=1, source="controller",
    )
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(planned, foreign)


def test_review_f33_residual_crafted_terminal_owned_artefact_retained(tmp_path):
    """    F33's residual, pinned (the review brief's question 1b): retention
    leaves no state record, so a crafted `{terminal_attempt}-artefact` id with
    no prior ARTEFACT_ADMITTED anywhere in the log is retained rather than
    refused. This is the fail-closed clause's renamed boundary: true for an id
    no terminal attempt owns, not for an id never admitted."""
    repo, commit = _make_repo(str(tmp_path))
    dimension, amount = "MODEL_COST", 10.0
    spec = _raw_spec(repo, commit, "RUN-GHOST", "true")
    store_path = os.path.join(str(tmp_path), "ghost.db")
    store = EventStore(store_path)
    try:
        controller, _target, run_id, root = run_entry.build_run(
            spec, store=store, workdir=str(tmp_path)
        )
        attempt_id = controller.plan_attempt(
            run_id, root, {"amount": amount, "dimension": dimension}
        )
        controller._emit(
            run_id, "ACTION_DISPATCHED",
            {"attempt_id": attempt_id, "executor": "command-executor-v1"},
            f"dispatch-{attempt_id}",
        )
        second = EventStore(store_path)
        try:
            run_entry.stop_run(second, run_id)
        finally:
            second.close()
        # the crafted id: the attempt is durably terminal and NO artefact
        # event of any kind is in this run's log.
        state = store.replay_fresh(run_id)
    finally:
        store.close()
    ghost = events.make_event(
        "ARTEFACT_INTEGRATED",
        {"artefact_id": f"{attempt_id}-artefact", "merge_info": {}},
        idempotency_key="probe-ghost", schema_version=1, policy_version=1,
        source="controller",
    )
    new_state, effects = reducer.reduce(state, ghost)
    assert [effect.kind for effect in effects] == ["late_event_retained"], (
        "F33 residual: the crafted terminal-owned id is retained, not refused, "
        "even though no admission for it exists anywhere in the log"
    )
    assert f"{attempt_id}-artefact" not in new_state.artefacts


def test_review_f30_accepted_lineage_settle_twice_lands_exactly_one_event(tmp_path):
    """F30's settle-once claim driven past its pin: the accepted lineage's
    terminal settle called twice lands exactly one NODE_MARKED_INFEASIBLE (the
    shared key's idempotency dedupes the second call), never a second event."""
    from orchestrator.controller import Controller
    from orchestrator.executor import ScriptedExecutor

    repo, commit = _make_repo(str(tmp_path))
    write = ("python3 -c \"open('src/app.py','w').write('def value():\\n"
             "    return 1\\n'); print('visible ok')\"")
    spec = _raw_spec(repo, commit, "RUN-STW", write)
    store = EventStore(os.path.join(str(tmp_path), "stw.db"))
    try:
        result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        assert result.outcome == "ACCEPTANCE_CLAIMED"
        controller = Controller(store, ScriptedExecutor({}))
        controller.record_failure(
            result.run_id, result.root_node_id,
            action_type="EXECUTE", diagnostic_category="LATE_ON_TERMINAL",
        )
        controller.mark_infeasible(result.run_id, result.root_node_id)
        count = sum(
            event.event_type == "NODE_MARKED_INFEASIBLE"
            for event in store.history(result.run_id)
        )
        assert count == 1
        before = len(store.history(result.run_id))
        controller.mark_infeasible(result.run_id, result.root_node_id)
        types = [event.event_type for event in store.history(result.run_id)]
        assert types.count("NODE_MARKED_INFEASIBLE") == 1, (
            "F30: the accepted lineage's settle twice must land exactly one "
            "terminal decision"
        )
        assert len(store.history(result.run_id)) == before
        state = store.state(result.run_id)
        assert state.nodes[result.root_node_id].state == "ACCEPTED"
        assert state.outcome == "ACCEPTANCE_CLAIMED"
    finally:
        store.close()


def test_review_f34_unparseable_spec_file_refused_as_a_named_run_spec_error(tmp_path):
    """F34: docs/run-entry.md's fail-closed loading claim — "a loader-refusable
    malformed spec is refused as a named `RunSpecError`" — does not hold for a
    spec file the YAML decoder itself cannot parse: `load_run_spec` catches
    only OSError, so the documented CLI head dies on a raw ParserError
    traceback instead of the named refusal. Red at FINAL; the next step's
    loader widening (or the sentence's re-scoping) absorbs this green."""
    bad = tmp_path / "BAD.yaml"
    bad.write_text("run_id: [unclosed\n  - oops\n")
    try:
        run_entry.load_run_spec(str(bad))
    except run_entry.RunSpecError:
        return  # the documented named refusal shape — after the widening
    except Exception as error:  # noqa: BLE001
        pytest.fail(
            f"F34: an unparseable spec file is refused as "
            f"{type(error).__name__}, not the documented named `RunSpecError`: "
            f"{error!r}"
        )
    pytest.fail("F34: the loader accepted an unparseable spec file")
