
"""HTTP endpoints the browser uses: /voice (one-shot), /transcribe, /plan, /execute."""

from __future__ import annotations

from app.agent import runner
from app.config import settings
from tests.conftest import tool_call

AUDIO = ("voice.webm", b"\x1aE\xdf\xa3" + b"\x00" * 400, "audio/webm")


def test_voice_endpoint_transcribes_and_plans_in_one_request(client, leads, fake_openai):
    fake = fake_openai(
        [[tool_call("send_follow_up_email", lead="Sarah Jenkins")]],
        transcript="Send the follow-up to Sarah Jenkins",
    )

    res = client.post("/api/agent/voice", files={"file": AUDIO})

    assert res.status_code == 200, res.text
    body = res.json()
    assert body["transcript"] == "Send the follow-up to Sarah Jenkins"
    assert [a["tool"] for a in body["actions"]] == ["send_follow_up_email"]
    assert set(body["timings_ms"]) == {"transcribe", "plan", "total"}
    assert len(fake.stt_calls) == 1 and len(fake.chat_calls) == 1


def test_transcription_uses_fast_model_language_and_vocab_prompt(client, fake_openai):
    fake = fake_openai([], transcript="show warm leads")

    res = client.post("/api/agent/transcribe", files={"file": AUDIO})

    assert res.status_code == 200
    kwargs = fake.stt_calls[0]
    assert kwargs["model"] == "gpt-4o-mini-transcribe"
    assert kwargs["language"] == "en"
    assert "follow-up" in kwargs["prompt"]
    assert kwargs["file"].name == "voice.webm"  # extension tells the API the format


def test_transcription_language_can_be_auto(client, fake_openai, monkeypatch):
    monkeypatch.setattr(settings, "openai_stt_language", "")
    fake = fake_openai([], transcript="hi")

    client.post("/api/agent/transcribe", files={"file": AUDIO})

    assert "language" not in fake.stt_calls[0]


def test_empty_audio_is_rejected(client, fake_openai):
    fake_openai([])
    res = client.post("/api/agent/voice", files={"file": ("v.webm", b"", "audio/webm")})
    assert res.status_code == 400


def test_silence_gives_clear_error(client, fake_openai):
    fake_openai([], transcript="")
    res = client.post("/api/agent/voice", files={"file": AUDIO})
    assert res.status_code == 400
    assert "Could not transcribe" in res.json()["detail"]


def test_missing_api_key_returns_503(client, monkeypatch):
    monkeypatch.setattr(settings, "openai_api_key", "")
    runner._build_client.cache_clear()
    res = client.post("/api/agent/voice", files={"file": AUDIO})
    assert res.status_code == 503
    assert "OPENAI_API_KEY" in res.json()["detail"]


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

    plan = client.post("/api/agent/plan", json={"transcript": "mark FU 1 done for Tom Baker"}).json()
    actions = [{"tool": a["tool"], "args": a["args"]} for a in plan["actions"]]
    res = client.post("/api/agent/execute", json={"transcript": plan["transcript"], "actions": actions})

    assert res.status_code == 200
    assert res.json()["success"] is True
    lead = client.get(f"/api/leads/{leads['tom_b'].id}").json()
    fu1 = next(f for f in lead["follow_ups"] if f["number"] == 1)
    assert fu1["status"] == "done"


def test_openai_client_is_reused(monkeypatch):
    """One shared client = one pooled HTTPS connection instead of a new TLS handshake per call."""
    runner._build_client.cache_clear()
    monkeypatch.setattr(settings, "openai_api_key", "k1")
    assert runner._openai_client() is runner._openai_client()
    runner._build_client.cache_clear()
