
"""Planning (dry run): correct tools, few model calls, and nothing is changed."""

from __future__ import annotations

from app.agent import runner
from app.config import settings
from app.models import EmailLog, FollowUp
from tests.conftest import text_reply, tool_call


def _fu_statuses(db, lead):
    db.expire_all()
    return [f.status for f in db.query(FollowUp).filter_by(lead_id=lead.id).order_by(FollowUp.number)]


# ------------------------------------------------------------------ speed


def test_send_to_named_person_uses_one_model_call(db, leads, fake_openai):
    fake = fake_openai([[tool_call("send_follow_up_email", lead="Sarah Jenkins")]])

    result = runner.plan_from_transcript(db, "Send the follow-up to Sarah Jenkins")

    assert len(fake.chat_calls) == 1, "should not need a resolve round or a summary round"
    [action] = result["actions"]
    assert action["tool"] == "send_follow_up_email"
    assert action["status"] == "planned"
    assert action["preview"]["to"] == "sarah@example.com"
    assert action["preview"]["follow_up_number"] == 1
    # Plan pins the exact lead + FU so Approve executes what was previewed
    assert action["args"]["lead_id"] == leads["sarah"].id
    assert action["args"]["fu_number"] == 1
    assert "Sarah Jenkins" in result["summary"]
    assert result["needs_disambiguation"] is False


def test_fast_settings_are_sent_to_reasoning_model(db, leads, fake_openai):
    fake = fake_openai([[tool_call("send_follow_up_email", lead="Sarah")]])

    runner.plan_from_transcript(db, "Send follow-up to Sarah")

    kwargs = fake.chat_calls[0]
    assert kwargs["model"] == "gpt-5-nano"
    assert kwargs["reasoning_effort"] == "minimal"
    assert kwargs["tool_choice"] == "required"  # first round must pick a tool
    assert "temperature" not in kwargs  # reasoning models reject it


def test_non_reasoning_model_uses_temperature(db, leads, fake_openai, monkeypatch):
    monkeypatch.setattr(settings, "openai_model", "gpt-4o-mini")
    fake = fake_openai([[tool_call("send_follow_up_email", lead="Sarah")]])

    runner.plan_from_transcript(db, "Send follow-up to Sarah")

    kwargs = fake.chat_calls[0]
    assert "reasoning_effort" not in kwargs
    assert kwargs["temperature"] == 0.1


def test_o_series_minimal_effort_is_mapped_to_low(db, leads, fake_openai, monkeypatch):
    monkeypatch.setattr(settings, "openai_model", "o4-mini")
    fake = fake_openai([[tool_call("send_follow_up_email", lead="Sarah")]])

    runner.plan_from_transcript(db, "Send follow-up to Sarah")

    assert fake.chat_calls[0]["reasoning_effort"] == "low"


def test_pure_lookup_skips_the_model_entirely(db, leads, fake_openai):
    fake = fake_openai([])  # any model call would raise

    result = runner.plan_from_transcript(db, "show me the warm leads")

    assert fake.chat_calls == []
    [action] = result["actions"]
    assert action["tool"] == "resolve_leads"
    names = {l["contact_name"] for l in action["preview"]["leads"]}
    assert names == {"Sarah Jenkins", "Olivia Old"}


# ----------------------------------------------------------------- dry run


def test_plan_does_not_send_or_change_anything(db, leads, fake_openai, monkeypatch):
    def boom(*a, **k):
        raise AssertionError("plan must never send email")

    monkeypatch.setattr("app.agent.tools.send_follow_up_email", boom)
    fake_openai([[tool_call("send_follow_up_email", lead="Sarah Jenkins")]])

    runner.plan_from_transcript(db, "Send the follow-up to Sarah Jenkins")

    assert _fu_statuses(db, leads["sarah"]) == ["pending"] * 7
    assert db.query(EmailLog).count() == 0


def test_mark_done_does_not_plan_an_email(db, leads, fake_openai):
    fake_openai([[tool_call("mark_follow_up_done", lead="Tom Baker", fu_number=1)]])

    result = runner.plan_from_transcript(db, "Mark follow-up 1 done for Tom Baker")

    assert [a["tool"] for a in result["actions"]] == ["mark_follow_up_done"]
    assert _fu_statuses(db, leads["tom_b"])[0] == "pending"  # still dry run


def test_mark_done_without_number_uses_next_pending(db, leads, fake_openai):
    fake_openai([[tool_call("mark_follow_up_done", lead="Tom Baker")]])

    result = runner.plan_from_transcript(db, "Mark Tom Baker's follow-up done")

    assert result["actions"][0]["preview"]["follow_up_number"] == 1


# --------------------------------------------------------- safety / errors


def test_ambiguous_name_asks_instead_of_guessing(db, leads, fake_openai):
    fake_openai([[tool_call("send_follow_up_email", lead="Tom")]])

    result = runner.plan_from_transcript(db, "send follow up to Tom")

    assert result["needs_disambiguation"] is True
    [action] = result["actions"]
    assert action["status"] == "failed"
    assert {l["contact_name"] for l in action["preview"]["leads"]} == {"Tom Baker", "Tom Hardy"}


def test_model_cannot_email_everyone_after_vague_lookup(db, leads, fake_openai):
    """Model resolves 'Tom' (2 hits) → we stop before it can send to both."""
    fake = fake_openai(
        [
            [tool_call("resolve_leads", query="Tom")],
            [tool_call("send_follow_up_email", lead_id=2), tool_call("send_follow_up_email", lead_id=3)],
        ]
    )

    result = runner.plan_from_transcript(db, "send follow up to Tom")

    assert len(fake.chat_calls) == 1, "second (sending) round must never happen"
    assert result["needs_disambiguation"] is True
    assert not any(a["tool"] == "send_follow_up_email" for a in result["actions"])
    assert "Tom Baker" in result["summary"] and "Tom Hardy" in result["summary"]


def test_exact_full_name_is_not_ambiguous(db, leads, fake_openai):
    fake_openai([[tool_call("send_follow_up_email", lead="Tom Baker")]])

    result = runner.plan_from_transcript(db, "send follow up to Tom Baker")

    assert result["needs_disambiguation"] is False
    assert result["actions"][0]["preview"]["to"] == "tom@example.com"


def test_unknown_person_returns_clear_error(db, leads, fake_openai):
    fake_openai([[tool_call("send_follow_up_email", lead="Zed Nobody")]])

    result = runner.plan_from_transcript(db, "send follow up to Zed Nobody")

    assert result["actions"][0]["status"] == "failed"
    assert any("No lead matches 'Zed Nobody'" in e for e in result["errors"])


def test_batch_send_to_overdue_leads(db, leads, fake_openai):
    fake = fake_openai(
        [
            [tool_call("resolve_leads", overdue_only=True)],
            [tool_call("send_follow_up_email", lead_id=leads["old"].id)],
        ]
    )

    result = runner.plan_from_transcript(db, "send follow ups to all overdue leads")

    assert len(fake.chat_calls) == 2  # resolve, then act — no summary round
    sends = [a for a in result["actions"] if a["tool"] == "send_follow_up_email"]
    assert [s["preview"]["contact_name"] for s in sends] == ["Olivia Old"]


def test_batch_is_capped_at_five_actions(db, leads, fake_openai):
    calls = [tool_call("append_lead_note", lead_id=leads["sarah"].id, text=f"n{i}") for i in range(7)]
    fake_openai([calls])

    result = runner.plan_from_transcript(db, "add notes to all warm leads")

    assert sum(a["tool"] == "append_lead_note" for a in result["actions"]) == 5
    assert any("Only the first 5" in e for e in result["errors"])


def test_text_reply_falls_back_to_summary(db, leads, fake_openai):
    fake_openai([text_reply("I can only help with leads.")])

    result = runner.plan_from_transcript(db, "what's the weather")

    assert result["actions"] == []
    assert result["summary"] == "I can only help with leads."


def test_ambiguous_summary_is_friendly(db, leads, fake_openai):
    fake_openai([[tool_call("send_follow_up_email", lead="Tom")]])

    result = runner.plan_from_transcript(db, "send follow up to Tom")

    assert result["summary"] == "Several leads match — say which one: L-002 Tom Baker, L-003 Tom Hardy."
