# backend/tests/test_evaluator.py — event_bus → evaluator → enqueue
from sqlmodel import Session

from app.automation import evaluator
from app.automation.event_bus import EventBus
from app.automation.events import APPROVAL_ENQUEUED, AUTOMATION_MATCHED
from app.models import AutomationRule


def _factory(engine):
    def make():
        return Session(engine)

    return make


def test_low_rule_auto_executes_under_mixed(client, session):
    s, engine = session
    bus = EventBus()
    evaluator.register(bus, _factory(engine))
    bus.publish(
        AUTOMATION_MATCHED, {"trigger_key": "mail.뉴스레터", "ctx": {"title": "뉴스레터 묶음"}}
    )
    q = client.get("/api/approvals").json()
    autos = [a for a in q["done"] if a["source"] == "automation"]
    assert autos, "low 규칙이 mixed 에서 자동 실행되어 done 큐에 들어가야 한다"


def test_high_action_always_pending(client, session):
    s, engine = session
    bus = EventBus()
    s.add(
        AutomationRule(
            id="rh",
            name="송금 자동",
            cat="life",
            trigger="청구서 도착",
            cond=None,
            action="자동 송금하기",
            on=True,
        )
    )
    s.commit()
    evaluator.register(bus, _factory(engine))
    bus.publish(AUTOMATION_MATCHED, {"trigger_key": "life.청구서", "ctx": {}})
    q = client.get("/api/approvals").json()
    assert any(a["source"] == "automation" and a["risk"] == "high" for a in q["pending"])


def test_enqueued_event_published(client, session):
    s, engine = session
    bus = EventBus()
    evaluator.register(bus, _factory(engine))
    bus.publish(AUTOMATION_MATCHED, {"trigger_key": "mail.뉴스레터", "ctx": {}})
    assert any(e.type == APPROVAL_ENQUEUED for e in bus.history)


def test_publish_records_history():
    bus = EventBus()
    bus.publish(AUTOMATION_MATCHED, {"trigger_key": "x.y"})
    assert bus.history[-1].type == AUTOMATION_MATCHED
