"""Tests for LOCAL VOICE (browser Web Speech API + deterministic intent routing).

Required coverage:
  1. every supported intent returns the right shape ({intent, reply, data})
  2. an unknown command returns the not-understood reply and does NOT raise
  3. every voice command writes an audit event with the transcript and the intent
  4. the reply text is non-empty (it is what speechSynthesis speaks back)

Plus the HTTP surface: GET /voice, GET /api/voice/commands, POST /api/voice/command.
"""

from __future__ import annotations

import os
import tempfile

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-voice-test-")
os.environ["JARVIS_DB"] = os.path.join(_TMP, "test.db")
os.environ["JARVIS_MEMORY_DB"] = os.path.join(_TMP, "data", "jarvis.db")

from orchestrator import audit  # noqa: E402
from orchestrator import memory  # noqa: E402
from orchestrator import scheduling  # noqa: E402
from orchestrator import voice  # noqa: E402
from orchestrator.components import register_default_components  # noqa: E402
from orchestrator.db import init_db  # noqa: E402
from orchestrator.registry import REGISTRY  # noqa: E402


@pytest.fixture(autouse=True)
def fresh_db():
    db = os.environ["JARVIS_DB"]
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(db + suffix)
        except FileNotFoundError:
            pass
    init_db()
    audit.init_db()
    memory.init_db()
    scheduling.init_db()
    REGISTRY.clear()
    register_default_components(REGISTRY)
    yield
    REGISTRY.clear()
    register_default_components(REGISTRY)


@pytest.fixture
def client():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        yield c


# --------------------------------------------------------------------------
# 1. intent resolution is deterministic
# --------------------------------------------------------------------------

@pytest.mark.parametrize("transcript,expected", [
    ("status", voice.INTENT_STATUS),
    ("what's the status", voice.INTENT_STATUS),
    ("how many jobs", voice.INTENT_STATUS),
    ("opportunities", voice.INTENT_OPPORTUNITIES),
    ("top opportunities", voice.INTENT_OPPORTUNITIES),
    ("bots", voice.INTENT_BOTS),
    ("which bots", voice.INTENT_BOTS),
    ("audit", voice.INTENT_AUDIT),
    ("is the chain intact", voice.INTENT_AUDIT),
    ("tick", voice.INTENT_TICK),
    ("run a tick", voice.INTENT_TICK),
    ("help", voice.INTENT_HELP),
    ("what can you do", voice.INTENT_HELP),
])
def test_resolve_intent(transcript, expected):
    assert voice.resolve_intent(transcript) == expected


@pytest.mark.parametrize("transcript", [
    "gibberish nonsense", "make me a sandwich", "", "   ", "asdfghjkl", "!!!",
])
def test_unknown_transcripts_resolve_to_not_understood(transcript):
    assert voice.resolve_intent(transcript) == voice.INTENT_UNKNOWN


def test_resolution_is_case_and_punctuation_insensitive():
    assert voice.resolve_intent("  STATUS!!!  ") == voice.INTENT_STATUS
    assert voice.resolve_intent("Bots?") == voice.INTENT_BOTS


# --------------------------------------------------------------------------
# 2. each intent returns the right shape
# --------------------------------------------------------------------------

@pytest.mark.parametrize("transcript,intent", [
    ("status", voice.INTENT_STATUS),
    ("opportunities", voice.INTENT_OPPORTUNITIES),
    ("bots", voice.INTENT_BOTS),
    ("audit", voice.INTENT_AUDIT),
    ("tick", voice.INTENT_TICK),
    ("help", voice.INTENT_HELP),
])
def test_each_intent_returns_the_right_shape(transcript, intent):
    result = voice.handle_command(transcript, write_audit=False)

    assert set(result) >= {"transcript", "intent", "reply", "data", "ok", "understood"}
    assert result["intent"] == intent
    assert isinstance(result["reply"], str) and result["reply"].strip()
    assert isinstance(result["data"], dict) and result["data"]
    assert result["understood"] is True
    assert result["ok"] is True
    assert result["error"] is None
    assert result["transcript"] == transcript


def test_status_intent_returns_loop_counts():
    result = voice.handle_command("status", write_audit=False)
    data = result["data"]
    assert "counts" in data
    assert "jobs_total" in data
    assert isinstance(data["counts"], dict)
    assert "chain" in data
    assert "signals" in data
    assert "opportunities" in data
    assert "bots" in data
    assert "Loop status" in result["reply"]


def test_opportunities_intent_returns_top_scored():
    result = voice.handle_command("opportunities", write_audit=False)
    data = result["data"]
    assert "opportunities" in data
    assert "count" in data
    assert isinstance(data["opportunities"], list)
    for opp in data["opportunities"]:
        assert {"id", "title", "composite_score", "status"} <= set(opp)


def test_bots_intent_returns_specs_and_verdicts():
    result = voice.handle_command("bots", write_audit=False)
    data = result["data"]
    assert "bots" in data
    assert "counts" in data
    assert data["deployed"] is False
    for bot in data["bots"]:
        assert {"id", "bot_name", "status", "verdict"} <= set(bot)


def test_audit_intent_returns_chain_length_and_integrity():
    result = voice.handle_command("audit", write_audit=False)
    data = result["data"]
    assert data["ok"] is True
    assert isinstance(data["length"], int)
    assert data["length"] >= 0
    assert "head_hash" in data
    assert "Audit chain intact" in result["reply"]


def test_tick_intent_runs_one_tick_and_reports_it():
    sched = scheduling.create_schedule("voice tick", "measure", cadence="daily",
                                       at_hour=9, at_minute=0)
    from datetime import datetime, timedelta, timezone
    from orchestrator.db import connect

    conn = connect()
    try:
        conn.execute("UPDATE schedules SET next_run_at = ? WHERE id = ?",
                     (scheduling.iso(datetime.now(timezone.utc) - timedelta(minutes=1)),
                      sched["id"]))
        conn.commit()
    finally:
        conn.close()

    result = voice.handle_command("tick", write_audit=False)
    data = result["data"]
    assert "fired" in data
    assert "fired_count" in data
    assert data["fired_count"] == 1
    assert data["fired"][0]["schedule_id"] == sched["id"]
    assert "Scheduler tick fired 1 schedule" in result["reply"]
    assert "Nothing fires on its own" in result["reply"]


def test_help_intent_lists_the_commands():
    result = voice.handle_command("help", write_audit=False)
    data = result["data"]
    assert "commands" in data
    assert len(data["commands"]) == len(voice.COMMANDS)
    assert "intents" in data
    for name in ("status", "opportunities", "bots", "audit", "tick", "help"):
        assert name in result["reply"]


# --------------------------------------------------------------------------
# 3. unknown command: not-understood, never raises
# --------------------------------------------------------------------------

def test_unknown_command_returns_not_understood_and_does_not_raise():
    result = voice.handle_command("gibberish nonsense", write_audit=False)

    assert result["intent"] == voice.INTENT_UNKNOWN
    assert result["understood"] is False
    assert result["ok"] is False
    assert result["error"] is None
    assert "didn't understand" in result["reply"]
    assert "gibberish nonsense" in result["reply"]
    assert "I won't guess" in result["reply"]
    # it offers the command list instead of guessing
    assert result["data"]["matched"] is False
    assert result["data"]["commands"]
    for name in ("status", "opportunities", "bots", "audit", "tick", "help"):
        assert name in result["reply"]


def test_empty_transcript_is_not_understood_and_does_not_raise():
    result = voice.handle_command("", write_audit=False)
    assert result["intent"] == voice.INTENT_UNKNOWN
    assert result["understood"] is False
    assert "didn't catch that" in result["reply"]


def test_none_transcript_does_not_raise():
    result = voice.handle_command(None, write_audit=False)
    assert result["intent"] == voice.INTENT_UNKNOWN
    assert result["reply"]


# --------------------------------------------------------------------------
# 4. audit
# --------------------------------------------------------------------------

def test_voice_command_writes_an_audit_event():
    before = audit.verify()["length"]
    result = voice.handle_command("status", source="browser")

    assert result["audit_seq"]
    rows = audit.recent(limit=20, actor=voice.COMPONENT_NAME, action="voice.command")
    assert rows, "every voice command must be recorded"
    row = rows[0]
    assert row["payload"]["transcript"] == "status"
    assert row["payload"]["intent"] == voice.INTENT_STATUS
    assert row["payload"]["understood"] is True
    assert row["payload"]["audio_uploaded"] is False
    assert row["payload"]["source"] == "browser"

    state = audit.verify()
    assert state["ok"] is True
    assert state["length"] > before


def test_unknown_voice_command_is_also_audited():
    voice.handle_command("gibberish nonsense")
    rows = audit.recent(limit=20, actor=voice.COMPONENT_NAME, action="voice.command")
    assert rows[0]["payload"]["transcript"] == "gibberish nonsense"
    assert rows[0]["payload"]["intent"] == voice.INTENT_UNKNOWN
    assert rows[0]["payload"]["understood"] is False


def test_audit_can_be_disabled_for_pure_routing():
    before = audit.verify()["length"]
    result = voice.handle_command("status", write_audit=False)
    assert "audit_seq" not in result
    assert audit.verify()["length"] == before


# --------------------------------------------------------------------------
# 5. HTTP surface
# --------------------------------------------------------------------------

def test_voice_page_renders_mic_and_command_list(client):
    resp = client.get("/voice")
    assert resp.status_code == 200
    body = resp.get_data(as_text=True)
    assert 'id="mic"' in body                      # the big mic button
    assert "webkitSpeechRecognition" in body       # real recognition
    assert "SpeechRecognition" in body
    assert "speechSynthesis" in body               # real synthesis
    assert "getVoices" in body                     # the voice picker
    assert "/api/voice/command" in body            # the command console
    assert "not understood" in body.lower()
    assert "no audio is uploaded" in body.lower()
    for name in ("status", "opportunities", "bots", "audit", "tick", "help"):
        assert name in body


def test_api_voice_commands_lists_intents(client):
    resp = client.get("/api/voice/commands")
    assert resp.status_code == 200
    body = resp.get_json()
    assert body["component"] == voice.COMPONENT_NAME
    assert body["api_key_required"] is False
    assert body["audio_uploaded_to_server"] is False
    intents = {c["intent"] for c in body["commands"]}
    assert intents == {"status", "opportunities", "bots", "audit", "tick", "help"}


def test_api_voice_command_status(client):
    resp = client.post("/api/voice/command", json={"transcript": "status"})
    assert resp.status_code == 200
    body = resp.get_json()
    assert body["intent"] == "status"
    assert isinstance(body["reply"], str) and body["reply"]
    assert "counts" in body["data"]
    assert body["audit_seq"]


def test_api_voice_command_unknown(client):
    resp = client.post("/api/voice/command", json={"transcript": "gibberish nonsense"})
    assert resp.status_code == 200
    body = resp.get_json()
    assert body["intent"] == "not_understood"
    assert body["understood"] is False
    assert "didn't understand" in body["reply"]
    assert body["data"]["matched"] is False


def test_api_voice_command_missing_transcript_is_not_an_error(client):
    resp = client.post("/api/voice/command", json={})
    assert resp.status_code == 200
    assert resp.get_json()["intent"] == "not_understood"


def test_voice_console_is_registered_as_a_tool():
    component = REGISTRY.get(voice.COMPONENT_NAME)
    assert component is not None
    assert component.handles_state is None
