# SPDX-License-Identifier: AGPL-3.0-or-later
"""Static-analysis gates.

These encode the cheap static checks from the recommendation: blind-except and
try/except/pass are hard failures, and the repo-specific numeric and shape
anti-patterns (an unguarded ``float`` on an event payload, iterating a mapping
value that defaults to an empty list) are reported. Branch coverage of the
frozen conformance corpus is held to a pinned floor so coverage cannot be
silently deleted.

The hard gates currently report findings; each failure is a defect reported by
this suite, not a regression.
"""
from __future__ import annotations

import ast
import pathlib
import re
import subprocess
import sys

import pytest

from orchestrator import conformance, reducer
from orchestrator.model import RunState

PROJECT_ROOT = pathlib.Path(__file__).resolve().parent.parent
PACKAGE_DIR = PROJECT_ROOT / "src" / "orchestrator"

# Pinned floor for branch coverage of the orchestrator package over the frozen
# corpus replay. A floor, not a correctness proof. Measured at ~50% when
# pinned; set below that so ordinary changes do not trip it, while deleting
# corpus coverage does.
CORPUS_COVERAGE_FLOOR = 48.0

FLOAT_ON_EVENT_FIELD = re.compile(r"float\(\s*(?:payload|commitment)\s*[\[.]")


def _source_files():
    return sorted(PACKAGE_DIR.glob("*.py"))


def test_no_blind_or_swallowed_exceptions():
    result = subprocess.run(
        [
            sys.executable,
            "-m",
            "ruff",
            "check",
            "--select",
            "BLE001,S110",
            "--no-cache",
            "--output-format",
            "concise",
            "src/orchestrator",
        ],
        cwd=PROJECT_ROOT,
        capture_output=True,
        text=True,
    )
    assert result.returncode == 0, (
        "blind or swallowed exceptions (BLE001/S110):\n" + result.stdout + result.stderr
    )


def test_event_payload_numbers_are_finiteness_checked_before_float():
    offenders = []
    for path in _source_files():
        for number, line in enumerate(path.read_text().splitlines(), start=1):
            if FLOAT_ON_EVENT_FIELD.search(line):
                offenders.append(f"{path.relative_to(PROJECT_ROOT)}:{number}: {line.strip()}")
    assert not offenders, (
        "float() applied directly to an event payload field without a finiteness "
        "check:\n" + "\n".join(offenders)
    )


def test_no_iteration_over_a_mapping_value_defaulting_to_an_empty_list():
    offenders = []
    for path in _source_files():
        tree = ast.parse(path.read_text())
        for node in ast.walk(tree):
            if (
                isinstance(node, ast.For)
                and isinstance(node.iter, ast.BoolOp)
                and isinstance(node.iter.op, ast.Or)
            ):
                offenders.append(f"{path.relative_to(PROJECT_ROOT)}:{node.lineno}")
    assert not offenders, (
        "iteration over a mapping value defaulting to an empty list accepts a "
        "scalar and iterates it:\n" + "\n".join(offenders)
    )


def test_frozen_corpus_branch_coverage_meets_the_floor(tmp_path):
    coverage = pytest.importorskip("coverage")
    if coverage.Coverage.current() is not None:
        pytest.skip("coverage is already running (pytest-cov)")
    measured = coverage.Coverage(
        branch=True, data_file=None, include=[str(PACKAGE_DIR / "*.py")]
    )
    measured.start()
    try:
        runs = conformance.build_corpus(str(tmp_path))
        for run in runs:
            state = RunState(run_id=run.run_id)
            for event in run.store.history(run.run_id):
                state, _ = reducer.reduce(state, event)
            run.store.close()
    finally:
        measured.stop()
    total = measured.report(show_missing=False)
    assert total >= CORPUS_COVERAGE_FLOOR, (
        f"corpus branch coverage fell to {total:.1f}% (floor {CORPUS_COVERAGE_FLOOR}%)"
    )


def test_clock_can_be_pinned_for_deterministic_timer_tests():
    time_machine = pytest.importorskip("time_machine")
    import time

    with time_machine.travel(1_000_000.0):
        assert time.time() == 1_000_000.0
