
"""Approve step: executing confirmed actions really changes the DB (email mocked)."""

from __future__ import annotations

from app.agent import runner
from app.models import FollowUp, Lead


def _fu(db, lead, number):
    db.expire_all()
    return db.query(FollowUp).filter_by(lead_id=lead.id, number=number).one()


def test_execute_mark_done(db, leads):
    result = runner.execute_actions(
        db, [{"tool": "mark_follow_up_done", "args": {"lead_id": leads["tom_b"].id, "fu_number": 1}}]
    )

    assert result["success"] is True
    assert _fu(db, leads["tom_b"], 1).status == "done"


def test_execute_send_calls_email_service_once(db, leads, monkeypatch):
    sent = []

    def fake_send(db_, lead, number, *, dry_run, transcript_snippet=None):
        sent.append((lead.contact_name, number, dry_run))
        return {"lead_id": lead.id, "follow_up_number": number, "status": "sent"}

    monkeypatch.setattr("app.agent.tools.send_follow_up_email", fake_send)

    result = runner.execute_actions(
        db,
        [{"tool": "send_follow_up_email", "args": {"lead_id": leads["sarah"].id, "fu_number": 1}}],
        transcript="send follow up to sarah",
    )

    assert result["success"] is True
    assert sent == [("Sarah Jenkins", 1, False)]


def test_plan_then_approve_round_trip(db, leads, fake_openai, monkeypatch):
    """What the UI does: plan → user clicks Approve → execute the planned args."""
    from tests.conftest import tool_call

    sent = []
    monkeypatch.setattr(
        "app.agent.tools.send_follow_up_email",
        lambda db_, lead, n, **k: sent.append((lead.lead_code, n)) or {"status": "sent"},
    )
    fake_openai([[tool_call("send_follow_up_email", lead="Sarah")]])

    plan = runner.plan_from_transcript(db, "send follow up to Sarah")
    approved = [{"tool": a["tool"], "args": a["args"]} for a in plan["actions"] if not a["error"]]
    result = runner.execute_actions(db, approved, transcript=plan["transcript"])

    assert result["success"] is True
    assert sent == [("L-001", 1)]


def test_execute_update_stage(db, leads):
    result = runner.execute_actions(
        db, [{"tool": "update_lead_stage", "args": {"lead_id": leads["tom_b"].id, "stage": "Won"}}]
    )

    assert result["success"] is True
    db.expire_all()
    assert db.get(Lead, leads["tom_b"].id).stage == "Won"


def test_execute_append_note(db, leads):
    runner.execute_actions(
        db, [{"tool": "append_lead_note", "args": {"lead_id": leads["tom_b"].id, "text": "Called, keen"}}]
    )

    db.expire_all()
    assert "Called, keen" in db.get(Lead, leads["tom_b"].id).notes


def test_execute_rejects_unknown_tool_and_bad_stage(db, leads):
    result = runner.execute_actions(
        db,
        [
            {"tool": "delete_everything", "args": {}},
            {"tool": "update_lead_stage", "args": {"lead_id": leads["tom_b"].id, "stage": "Bogus"}},
        ],
    )

    assert result["success"] is False
    assert any("Cannot execute tool: delete_everything" in e for e in result["errors"])
    assert any("Invalid stage" in e for e in result["errors"])


def test_execute_with_ambiguous_name_does_nothing(db, leads):
    result = runner.execute_actions(
        db, [{"tool": "mark_follow_up_done", "args": {"lead": "Tom", "fu_number": 1}}]
    )

    assert result["success"] is False
    assert _fu(db, leads["tom_b"], 1).status == "pending"
    assert _fu(db, leads["tom_h"], 1).status == "pending"
