"""Proactive outreach: the decision rule, the briefing, and the one write."""
from datetime import datetime, timedelta, timezone

import pytest

from orchestrator import proactive

NOW = datetime(2026, 11, 24, 12, 0, tzinfo=timezone.utc)


def _hours_ago(hours):
    return (NOW - timedelta(hours=hours)).strftime("%Y-%m-%dT%H:%M:%SZ")


@pytest.fixture
def quiet(monkeypatch):
    """Nothing wrong anywhere."""
    monkeypatch.setattr(proactive.audit, "verify", lambda: {"ok": True, "detail": "ok"})
    monkeypatch.setattr(proactive.audit, "recent", lambda **kw: [])
    monkeypatch.setattr(proactive.outreach, "init_db", lambda: "")
    monkeypatch.setattr(proactive.outreach, "list_leads", lambda: [])
    monkeypatch.setattr(proactive.outreach, "list_drafts", lambda: [])
    monkeypatch.setattr("orchestrator.measurement.all_decisions", lambda *a, **kw: [])
    monkeypatch.setattr("orchestrator.bot_factory.list_specs", lambda **kw: [])
    return monkeypatch


def test_quiet_system_interrupts_nobody(quiet):
    report = proactive.survey(NOW)
    assert proactive.worth_interrupting(report) == []
    assert "nothing worth interrupting" in proactive.render(report)


def test_broken_chain_is_critical(quiet):
    quiet.setattr(proactive.audit, "verify", lambda: {"ok": False, "detail": "broken at 12"})
    report = proactive.survey(NOW)
    assert report["signals"][0]["kind"] == "chain.broken"
    assert report["signals"][0]["urgency"] == "critical"


def test_chain_verification_that_raises_is_still_reported(quiet):
    def boom():
        raise RuntimeError("db locked")
    quiet.setattr(proactive.audit, "verify", boom)
    report = proactive.survey(NOW)
    assert any(s["kind"] == "chain.broken" for s in report["signals"])


def test_lead_without_a_draft_interrupts(quiet):
    quiet.setattr(proactive.outreach, "list_leads", lambda: [
        {"id": 7, "business": "Hoffman Excavating", "category": "excavation", "city": "Canandaigua"},
    ])
    worth = proactive.worth_interrupting(proactive.survey(NOW))
    assert [s["kind"] for s in worth] == ["lead.undrafted"]
    assert "Hoffman Excavating" in worth[0]["reason"]


def test_lead_with_a_draft_does_not_interrupt(quiet):
    quiet.setattr(proactive.outreach, "list_leads", lambda: [{"id": 7, "business": "X"}])
    quiet.setattr(proactive.outreach, "list_drafts", lambda: [
        {"id": 1, "lead_id": 7, "status": "draft", "created_at": _hours_ago(1)},
    ])
    assert proactive.worth_interrupting(proactive.survey(NOW)) == []


def test_approved_draft_going_stale_is_high(quiet):
    quiet.setattr(proactive.outreach, "list_drafts", lambda: [
        {"id": 4, "lead_id": 1, "status": "approved", "approved_at": _hours_ago(31)},
    ])
    worth = proactive.worth_interrupting(proactive.survey(NOW))
    assert worth[0]["kind"] == "draft.stalled"
    assert worth[0]["urgency"] == "high"


def test_fresh_approved_draft_is_not_stalled(quiet):
    quiet.setattr(proactive.outreach, "list_drafts", lambda: [
        {"id": 4, "lead_id": 1, "status": "approved", "approved_at": _hours_ago(2)},
    ])
    assert proactive.worth_interrupting(proactive.survey(NOW)) == []


def test_unapproved_draft_waits_then_interrupts(quiet):
    quiet.setattr(proactive.outreach, "list_drafts", lambda: [
        {"id": 5, "lead_id": 1, "status": "draft", "created_at": _hours_ago(50)},
    ])
    worth = proactive.worth_interrupting(proactive.survey(NOW))
    assert [s["kind"] for s in worth] == ["draft.waiting"]


def _recording(value):
    """Wrap a fake so a test can assert it was actually used.

    A stale monkeypatch target lets a test pass on real data by accident -
    which is exactly how this test was order-dependent. Asserting the fake
    was called makes that impossible.
    """
    calls = []

    def wrapper(*args, **kwargs):
        calls.append((args, kwargs))
        return value(*args, **kwargs) if callable(value) else value

    wrapper.calls = calls
    return wrapper


def test_killed_bot_alone_does_not_interrupt(quiet):
    fake = _recording([
        {"bot_id": 3, "verdict": "KILLED", "created_at": _hours_ago(40)},
    ])
    quiet.setattr("orchestrator.measurement.all_decisions", fake)
    report = proactive.survey(NOW)
    assert fake.calls, (
        "all_decisions() was never called - the patch target is stale, so "
        "this test read the real database instead of the fake."
    )
    assert proactive.worth_interrupting(report) == []
    assert any(s["kind"] == "bot.killed" for s in report["signals"])
    assert "also noted" in proactive.render(report)


def test_high_score_opportunity_without_a_spec_interrupts(quiet):
    quiet.setattr(proactive.audit, "recent", lambda **kw: [
        {"action": "opportunity.created", "subject_id": "opp-9",
         "payload": {"opportunity_id": "opp-9", "composite_score": 77}},
    ])
    worth = proactive.worth_interrupting(proactive.survey(NOW))
    assert [s["kind"] for s in worth] == ["opportunity.unbuilt"]


def test_opportunity_that_already_has_a_spec_is_skipped(quiet):
    quiet.setattr("orchestrator.bot_factory.list_specs", lambda **kw: [{"opportunity_id": "opp-9"}])
    quiet.setattr(proactive.audit, "recent", lambda **kw: [
        {"action": "opportunity.created", "subject_id": "opp-9",
         "payload": {"opportunity_id": "opp-9", "composite_score": 77}},
    ])
    assert proactive.worth_interrupting(proactive.survey(NOW)) == []


def test_low_score_opportunity_is_ignored(quiet):
    quiet.setattr(proactive.audit, "recent", lambda **kw: [
        {"action": "opportunity.created", "subject_id": "opp-1",
         "payload": {"opportunity_id": "opp-1", "composite_score": 12}},
    ])
    assert proactive.worth_interrupting(proactive.survey(NOW)) == []


def test_unreadable_store_becomes_a_note_not_a_crash(quiet):
    def boom():
        raise RuntimeError("no such table")
    quiet.setattr(proactive.outreach, "list_leads", boom)
    report = proactive.survey(NOW)
    assert any("outreach store unreadable" in n for n in report["notes"])
    assert "could not read" in proactive.render(report)


def test_initiate_writes_nothing_when_quiet(quiet):
    calls = []
    quiet.setattr(proactive.audit, "record", lambda *a, **kw: calls.append((a, kw)) or {})
    result = proactive.initiate()
    assert result["initiated"] is False
    assert calls == []


def test_initiate_writes_one_row_when_there_is_something(quiet):
    quiet.setattr(proactive.outreach, "list_leads", lambda: [{"id": 7, "business": "Hoffman"}])
    calls = []
    quiet.setattr(proactive.audit, "record", lambda *a, **kw: calls.append((a, kw)) or {"seq": 99})
    result = proactive.initiate()
    assert result["initiated"] is True
    assert result["ledger_seq"] == 99
    assert len(calls) == 1
    args, kwargs = calls[0]
    assert args[1] == "proactive.initiated"
    assert kwargs["payload"]["kinds"] == ["lead.undrafted"]


def test_render_names_the_action(quiet):
    quiet.setattr(proactive.outreach, "list_leads", lambda: [
        {"id": 7, "business": "Hoffman Excavating", "category": "excavation", "city": "Canandaigua"},
    ])
    text = proactive.render(proactive.survey(NOW))
    assert "NORMAL" in text
    assert "lead.undrafted" in text
    assert "outreach.create_draft(7)" in text


def test_notify_is_silent_when_osascript_is_missing(monkeypatch):
    monkeypatch.setattr(proactive.shutil, "which", lambda name: None)
    ok, error = proactive.notify("t", "m")
    assert ok is False
    assert "osascript" in error


def test_applescript_string_escapes_quotes():
    assert proactive._applescript_string('say "hi"') == '"say \\"hi\\""'
