# SPDX-License-Identifier: AGPL-3.0-or-later
"""The kernel_id load refusal (FRK-1, owner ruling R11).

``validate_run_spec`` is the seam: when the ``project_kernel``
mapping carries a ``kernel_id`` key, its value must be a
non-empty string (whitespace-stripped) — dict, list, int, bool,
explicit null, empty, and whitespace-only all refuse as a named
:class:`RunSpecError` naming the value, before any store is
opened or any event is admitted. A missing key still passes
validation and falls back to the snapshot id in
``run_configuration``, whose ``str()``-coercion stays
byte-identical and becomes unreachable from a spec.

Two named shapes:

- ``kernel_id load refusal``: the wrong-typed matrix through
  ``validate_run_spec`` (loop form, failing named per member),
  plus one file-backed ``load_run_spec`` drive whose refusal
  leaves no store file in the tmp dir.
- ``kernel_id fallback``: a spec with no ``kernel_id`` key
  validates clean, and ``run_configuration`` against a stub
  target admits it with ``kernel_id`` equal to the snapshot id.
"""

from __future__ import annotations

import dataclasses
from typing import Any, Mapping, Tuple

import pytest
import yaml

from orchestrator import run_entry

pytestmark = pytest.mark.slow


def _spec(**overrides) -> dict:
    document = {
        "run_id": "RUN-KERNEL",
        "repository": "/tmp",
        "base_commit": "0" * 40,
        "snapshot_id": "TARGET-SNAPSHOT",
        "task_statement": "task",
        "executor_profile": "command-executor-v1",
        "project_kernel": {"kernel_id": "KERNEL-1"},
        "visible_commands": ["true"],
        "components": [["core", "src/a.py"]],
        "owned_scope": ["src/**"],
        "acceptance_criteria": ["AC-CORE"],
        "budgets": {"MODEL_COST": 1.0},
        "limits": {},
        "policy_version": 1,
        "evidence_policy": {"level": "MEDIUM", "version": 1},
    }
    document.update(overrides)
    return document


_WRONG_TYPED_KERNEL_IDS = (
    ({"a": 1}, "dict"),
    (["a"], "list"),
    (42, "int"),
    (True, "bool"),
    (None, "null"),
    ("", "empty"),
    ("   ", "whitespace"),
)


def test_kernel_id_load_refusal(tmp_path):
    """FRK-1: every present-but-wrong-typed ``kernel_id`` is
    refused as a named ``RunSpecError`` naming the value, and the
    file-backed load refuses with no store file created."""
    for value, label in _WRONG_TYPED_KERNEL_IDS:
        try:
            run_entry.validate_run_spec(
                _spec(project_kernel={"kernel_id": value})
            )
        except run_entry.RunSpecError as error:
            assert repr(value) in str(error), (
                f"FRK-1: the {label} kernel_id refusal does not "
                f"name the value: {error}"
            )
            continue
        pytest.fail(
            f"FRK-1: a {label} kernel_id was admitted by validate_run_spec"
        )

    # The file-backed head: a dict kernel_id refuses as a named
    # RunSpecError, and the refusal precedes any store open — no
    # store file is created in the tmp dir, so zero events are
    # admitted by construction.
    path = tmp_path / "spec.yaml"
    path.write_text(yaml.safe_dump(_spec(project_kernel={"kernel_id": {"a": 1}})))
    with pytest.raises(run_entry.RunSpecError) as raised:
        run_entry.load_run_spec(str(path))
    assert repr({"a": 1}) in str(raised.value)
    assert list(tmp_path.iterdir()) == [path]


def test_kernel_id_fallback():
    """The ``or snapshot_id`` fallback the fix preserves: a spec
    whose ``project_kernel`` carries no ``kernel_id`` key validates
    clean, and ``run_configuration`` admits it with ``kernel_id``
    equal to the snapshot id — the fallback and only the fallback."""
    spec = run_entry.validate_run_spec(
        _spec(project_kernel={"name": "kernel"})
    )
    assert "kernel_id" not in spec["project_kernel"]
    config = run_entry.run_configuration(spec, _stub_target(spec))
    assert config["project_kernel"]["kernel_id"] == spec["snapshot_id"]


@dataclasses.dataclass(frozen=True)
class _StubTarget:
    """The target's read fields alone — the eight attributes
    ``run_configuration`` reads; no git repository is built."""

    task_statement: str
    owned_scope: Tuple[str, ...]
    commit: str
    visible_commands: Tuple[str, ...]
    acceptance_criteria: Tuple[str, ...]
    project_kernel: Mapping[str, Any]
    snapshot_id: str
    contract_hash: str


def _stub_target(spec: Mapping[str, Any]) -> _StubTarget:
    return _StubTarget(
        task_statement=spec["task_statement"],
        owned_scope=tuple(spec["owned_scope"]),
        commit=spec["base_commit"],
        visible_commands=tuple(spec["visible_commands"]),
        acceptance_criteria=tuple(spec["acceptance_criteria"]),
        project_kernel=spec["project_kernel"],
        snapshot_id=spec["snapshot_id"],
        contract_hash="0" * 64,
    )
