from __future__ import annotations

import logging
import subprocess
from pathlib import Path
from types import SimpleNamespace

import pytest

from recoil.execution.step_types import PassResult
from recoil.core.critic import FailureMode
from recoil.pipeline.orchestrator import strategy_registry as sr


@pytest.fixture(autouse=True)
def _reset_classifier_warning() -> None:
    sr._warned_tier2_opus_unavailable = False


def test_classify_with_opus_none_client_warns_once(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
    caplog: pytest.LogCaptureFixture,
) -> None:
    from recoil.tools import engine_constants as tool_ec

    video_path = tmp_path / "failed.mp4"
    video_path.write_bytes(b"fake video")

    def fake_run(cmd, capture_output=True, timeout=15):
        Path(cmd[-1]).write_bytes(b"fake jpeg")
        return SimpleNamespace(returncode=0)

    monkeypatch.setattr(subprocess, "run", fake_run)
    monkeypatch.setattr(tool_ec, "get_anthropic_client", lambda: None)

    pass_result = PassResult(
        pass_id="pass-1",
        success=False,
        video_path=str(video_path),
        cost_usd=0.0,
    )

    with caplog.at_level(logging.WARNING, logger=sr.__name__):
        assert sr._classify_with_opus(pass_result) == (FailureMode.UNKNOWN, 0.30)
        assert sr._classify_with_opus(pass_result) == (FailureMode.UNKNOWN, 0.30)

    messages = [
        record.getMessage()
        for record in caplog.records
        if "Tier-2 Opus classifier unavailable" in record.getMessage()
    ]
    assert messages == [
        "Tier-2 Opus classifier unavailable (no Anthropic SDK client) — visual failures degrade to UNKNOWN/0.30"
    ]
