
"""End-to-end speed + accuracy check against the REAL OpenAI API.

Skipped by default (costs ~1 cent). Run with:

    RUN_LIVE_OPENAI=1 uv run pytest -m live -s

Uses the key from backend/.env, a throwaway SQLite DB, and dry-run plans only —
no email is ever sent and your real database is never touched.
Spoken audio is generated with OpenAI text-to-speech, so no microphone needed.
"""

from __future__ import annotations

import os
import time
from pathlib import Path

import pytest
from dotenv import dotenv_values

from app.agent import runner
from app.config import ENV_FILE, settings

pytestmark = [
    pytest.mark.live,
    pytest.mark.skipif(os.getenv("RUN_LIVE_OPENAI") != "1", reason="set RUN_LIVE_OPENAI=1"),
]

# Generous budgets so a slow network doesn't flake; typical is ~1-2s each.
MAX_STT_SECONDS = 6
MAX_PLAN_SECONDS = 8

CASES = [
    # (spoken command, expected tools, expected lead name or None, disambiguation?)
    ("Send the follow-up email to Sarah Jenkins", ["send_follow_up_email"], "Sarah Jenkins", False),
    ("Mark follow-up one done for Tom Baker", ["mark_follow_up_done"], "Tom Baker", False),
    ("Move Sarah Jenkins to proposal sent", ["update_lead_stage"], "Sarah Jenkins", False),
    ("Send a follow-up to Tom", None, None, True),
]


@pytest.fixture()
def real_openai(monkeypatch):
    key = dotenv_values(ENV_FILE).get("OPENAI_API_KEY") or ""
    if not key:
        pytest.skip("OPENAI_API_KEY missing in backend/.env")
    model = dotenv_values(ENV_FILE).get("OPENAI_MODEL") or "gpt-5-nano"
    monkeypatch.setattr(settings, "openai_api_key", key)
    monkeypatch.setattr(settings, "openai_model", model)
    runner._build_client.cache_clear()
    yield runner._openai_client()
    runner._build_client.cache_clear()


def _speech(client, text: str, cache_dir: Path) -> bytes:
    path = cache_dir / (text.replace(" ", "_")[:60] + ".mp3")
    if not path.exists():
        audio = client.audio.speech.create(model="tts-1", voice="alloy", input=text)
        path.write_bytes(audio.content)
    return path.read_bytes()


@pytest.mark.parametrize("spoken,tools,who,disamb", CASES, ids=[c[0] for c in CASES])
def test_voice_command_is_fast_and_correct(db, leads, real_openai, tmp_path_factory, spoken, tools, who, disamb):
    audio = _speech(real_openai, spoken, tmp_path_factory.getbasetemp())

    t0 = time.perf_counter()
    transcript = runner.transcribe_audio(audio, "voice.mp3")
    t1 = time.perf_counter()
    plan = runner.plan_from_transcript(db, transcript)
    t2 = time.perf_counter()

    print(
        f"\n  '{spoken}'\n   heard: {transcript!r}\n"
        f"   stt {t1 - t0:.2f}s | plan {t2 - t1:.2f}s | total {t2 - t0:.2f}s\n"
        f"   → {plan['summary']}"
    )
    assert t1 - t0 < MAX_STT_SECONDS, "speech-to-text too slow"
    assert t2 - t1 < MAX_PLAN_SECONDS, "planning too slow"

    assert plan["needs_disambiguation"] is disamb
    if tools:
        assert [a["tool"] for a in plan["actions"]] == tools
        assert all(a["status"] == "planned" for a in plan["actions"])
        assert plan["actions"][0]["preview"]["contact_name"] == who
