"""Backpressure/rejection contract tests."""

import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from feid.agent import AgenteMaestroNASA
from feid.core import ConfigAgente
import feid.agent.maestro as maestro_module


class DummyThread:
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

    def start(self):
        return None


class AgentBackpressure(AgenteMaestroNASA):
    def _technical_work(self, task):
        return f"ok:{task}"


@pytest.fixture
def agente(monkeypatch):
    monkeypatch.setattr(maestro_module.threading, "Thread", DummyThread)
    config = ConfigAgente(capacidad=10, max_workers=0, backpressure_threshold=0.5)
    return AgentBackpressure("BP", config=config, auto_persist=False)


def test_backpressure_returns_retry_after(monkeypatch, agente):
    for i in range(6):
        agente.send_task(f"t{i}")

    monkeypatch.setattr(agente.queue_manager, "apply_backpressure", lambda _max: 0.2)
    monkeypatch.setattr(maestro_module.time, "sleep", lambda *_: None)

    meta = agente.send_task("t-delay", backpressure=True, return_metadata=True)
    assert meta["accepted"] is True
    assert meta["retry_after"] == 0.2
    assert meta.get("reason") is None


def test_saturation_rejects_with_reason(monkeypatch):
    monkeypatch.setattr(maestro_module.threading, "Thread", DummyThread)
    config = ConfigAgente(capacidad=1, max_workers=0)
    agent = AgentBackpressure("SAT", config=config, auto_persist=False)

    agent.send_task("t1")
    meta = agent.send_task("t2", return_metadata=True)

    assert meta["accepted"] is False
    assert meta["reason"] == "SATURATION"
    assert meta["retry_after"] == 0.0
