# SPDX-License-Identifier: AGPL-3.0-or-later
"""The loader-refusal envelope: one seam over read, decode, parse, and construct.

R10 settles the loader's named-refusal contract: ``load_run_spec``'s try block
carries exactly two except clauses — ``except MemoryError: raise`` (the
host-resource boundary the ruling names) and ``except Exception as error: raise
RunSpecError(...) from error`` (the whole refusal face). This module pins both
named shapes of the brief:

- ``Loader-refusal envelope``: over hypothesis-generated YAML bytes that cross
  every safe-loader tag family with arbitrary scalars, splice invalid UTF-8, and
  recurse past the parser's stack, ``load_run_spec`` either returns a
  ``Mapping`` or raises ``RunSpecError`` — nothing else.
- ``Read-refusal pin``: the ``OSError`` read family (a missing path, a
  directory, a symlink loop) refuses as a named ``RunSpecError`` whose message
  names the path and whose ``__cause__`` is the underlying ``OSError``.

The three typed-scalar probes of ``tests/test_phase5_run_entry_fixes_6_review.py``
(F38/F39/F40) are the envelope's absorbed shape: they go green at FINAL with no
test edit, so this module does not rebuild them.
"""

from __future__ import annotations

from collections.abc import Mapping

import pytest
import yaml
from hypothesis import HealthCheck, given, settings, strategies as st

from orchestrator import run_entry

pytestmark = pytest.mark.slow


_SETTINGS = settings(
    derandomize=True,
    max_examples=50,
    deadline=None,
    suppress_health_check=[HealthCheck.too_slow],
)


_SAFE_TAGS = (
    "!!int",
    "!!float",
    "!!bool",
    "!!str",
    "!!null",
    "!!timestamp",
    "!!binary",
    "!!set",
    "!!omap",
    "!!seq",
    "!!map",
)

_PAYLOADS = (
    "garbage",
    "junk",
    "",
    " ",
    "~",
    "null",
    "true",
    "false",
    "yes",
    "no",
    "on",
    "off",
    "0",
    "1",
    "-1",
    "1.5",
    "1e3",
    "0x10",
    "0o17",
    "08",
    "12:34:56",
    "2001-12-14",
    "2020-13-45T99:99:99Z",
    "nope",
    "\u00e9",
    "\u2603",
    "!!",
    "!x",
    "&x",
    "*a",
    "?",
    "-",
    ":",
    "line1\nline2",
    "a: b",
    "[1, 2]",
    "{a: 1}",
    "<<",
    "0b101",
    "1_000",
    ".inf",
    ".nan",
    "-.inf",
)

_INVALID_UTF8 = (
    b"\xff",
    b"\xfe",
    b"\x80",
    b"\xc0\x80",
    b"\xed\xa0\x80",
    b"\xf5\xff",
    b"\xff\xfe",
)


def _render_yaml_scalar(payload: str, form: str) -> str:
    if form == "single":
        return "'" + payload.replace("'", "''") + "'"
    if form == "double":
        escaped = payload.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
        return '"' + escaped + '"'
    return payload


@st.composite
def _tagged_document(draw):
    """Cross every safe-loader tag family with one drawn scalar, plus the merge
    key, so each generated document carries a tagged value under every family."""
    payload = draw(st.one_of(st.sampled_from(_PAYLOADS), st.text(max_size=8)))
    form = draw(st.sampled_from(("single", "double", "plain")))
    rendered = _render_yaml_scalar(payload, form)
    lines = [f"k{index}: {tag} {rendered}\n" for index, tag in enumerate(_SAFE_TAGS)]
    lines.append("merge:\n  <<: {a: 1}\n")
    return "".join(lines).encode("utf-8")


@st.composite
def _spliced_document(draw):
    """Splice a raw invalid-UTF-8 sequence into a tagged document, so the bytes
    are written unwrapped and the decode stage sees them."""
    blob = draw(_tagged_document())
    splice = draw(st.sampled_from(_INVALID_UTF8))
    index = draw(st.integers(min_value=0, max_value=len(blob)))
    return blob[:index] + splice + blob[index:]


@st.composite
def _deep_document(draw):
    """Recursive flow at depths the parser overflows (F36's class)."""
    depth = draw(st.integers(min_value=1, max_value=2500))
    return b"deep: " + b"[" * depth + b"]" * depth + b"\n"


@st.composite
def _valid_document(draw):
    """A well-formed run-spec, so the returned-``Mapping`` arm of the property
    is exercised rather than only the refusal arm."""
    run_id = draw(st.sampled_from(("RUN-A", "RUN-B", "RUN-C")))
    document = {
        "run_id": run_id,
        "repository": "/repo",
        "base_commit": "0" * 40,
        "snapshot_id": f"TARGET-{run_id}",
        "task_statement": "task",
        "project_kernel": {"kernel_id": "K"},
        "visible_commands": ["true"],
        "components": [["core", "src/app.py"]],
        "owned_scope": ["src/**"],
        "acceptance_criteria": ["AC-CORE"],
        "budgets": {"MODEL_COST": 1.0},
        "limits": {"actions": 1},
        "policy_version": 1,
        "evidence_policy": {"level": "MEDIUM", "version": 1},
        "executor_profile": "command-executor-v1",
    }
    return yaml.safe_dump(document).encode("utf-8")


def _envelope_inputs():
    return st.one_of(
        _tagged_document(),
        _spliced_document(),
        _deep_document(),
        _valid_document(),
        st.binary(max_size=16),
    )


@_SETTINGS
@given(_envelope_inputs())
def test_loader_refusal_envelope(tmp_path_factory, payload_bytes):
    path = tmp_path_factory.mktemp("envelope") / "spec.yaml"
    path.write_bytes(payload_bytes)
    try:
        document = run_entry.load_run_spec(str(path))
    except run_entry.RunSpecError:
        return
    assert isinstance(document, Mapping)


def test_read_refusal_pin(tmp_path):
    missing = tmp_path / "missing.yaml"
    _assert_read_refusal(missing)

    directory = tmp_path / "a-directory"
    directory.mkdir()
    _assert_read_refusal(directory)

    loop = tmp_path / "symlink-loop"
    loop.symlink_to(loop)
    _assert_read_refusal(loop)


def _assert_read_refusal(path):
    try:
        run_entry.load_run_spec(str(path))
    except run_entry.RunSpecError as error:
        assert str(path) in str(error)
        assert isinstance(error.__cause__, OSError)
    else:
        pytest.fail(f"{path!r} was not refused as a named RunSpecError")
