"""Voice transcription logging and usage metering (HA-499).

Two things are being protected here, and both are the kind that fail silently:

  * what gets WRITTEN — a row for failures as well as successes, and no
    transcript text unless someone deliberately turned that on;
  * what gets METERED — against a FK whose violation record_usage swallows,
    and under a provider label that a copy-paste would get wrong.

Neither shows up in an end-to-end click-through, so neither is covered by
anything else.
"""

import logging

import pytest

import services.voice_log_service as voice_log_service


@pytest.fixture
def written(monkeypatch):
    """Collects the rows voice_log_service would have written."""
    rows = []
    monkeypatch.setattr(voice_log_service, "_write", lambda **kw: rows.append(kw))
    return rows


@pytest.fixture
def usage_calls(monkeypatch):
    """Collects the kwargs handed to quota_service.record_usage."""
    calls = []

    class _FakeSession:
        def close(self):
            pass

    monkeypatch.setattr(voice_log_service, "SessionLocal", lambda: _FakeSession())
    monkeypatch.setattr(voice_log_service.quota_service, "record_usage",
                        lambda db, **kw: calls.append(kw))
    return calls


# ── What gets written ────────────────────────────────────────────────────────

async def test_a_successful_attempt_is_recorded(written):
    await voice_log_service.log_attempt(
        user_id=7, company_id=1, status="success", audio_seconds=3.5,
        char_count=24, response_shape="whisperx_segments",
    )
    assert len(written) == 1
    assert written[0]["status"] == "success"
    assert written[0]["audio_seconds"] == 3.5


async def test_failures_are_recorded_too(written):
    """"The ASR was down for 20 minutes" is exactly the thing whose absence is
    indistinguishable from "logging broke"."""
    await voice_log_service.log_attempt(
        user_id=7, company_id=1, status="asr_error",
        error_code="asr_unavailable", upstream_status=503,
    )
    assert written[0]["status"] == "asr_error"
    assert written[0]["error_code"] == "asr_unavailable"
    assert written[0]["upstream_status"] == 503


async def test_transcript_text_is_dropped_by_default(written, monkeypatch):
    """Transcribed speech is personal data and already lands in `messages`
    once sent. A second copy under a different retention policy is liability."""
    monkeypatch.setattr(voice_log_service, "VOICE_STORE_TRANSCRIPT_TEXT", False)
    await voice_log_service.log_attempt(
        user_id=7, status="success", text="apply casual leave tomorrow",
    )
    assert "text" not in written[0]


async def test_transcript_text_is_kept_only_when_explicitly_enabled(written, monkeypatch):
    monkeypatch.setattr(voice_log_service, "VOICE_STORE_TRANSCRIPT_TEXT", True)
    await voice_log_service.log_attempt(
        user_id=7, status="success", text="apply casual leave tomorrow",
    )
    assert written[0]["text"] == "apply casual leave tomorrow"


async def test_logging_never_raises_into_the_request(monkeypatch):
    """A logging failure must not break a transcription the user is waiting on."""
    def boom(**kwargs):
        raise RuntimeError("database is on fire")

    monkeypatch.setattr(voice_log_service, "_write", boom)
    await voice_log_service.log_attempt(user_id=7, status="success")  # must not raise


def test_the_fingerprint_never_exposes_the_transcript():
    """Logs correlate on a hash, never on what the employee said."""
    fp = voice_log_service.text_fingerprint("apply casual leave tomorrow")
    assert "leave" not in fp
    assert len(fp) == 12
    assert fp == voice_log_service.text_fingerprint("apply casual leave tomorrow")
    assert fp != voice_log_service.text_fingerprint("something else")


# ── What gets metered ────────────────────────────────────────────────────────

async def test_observe_only_by_default_writes_no_usage_row(usage_calls, monkeypatch):
    """0 tokens/second means SKIP the call, not write a 0-token row. The
    duration still lands on voice_transcriptions, which is the real data."""
    monkeypatch.setattr(voice_log_service, "VOICE_TOKENS_PER_AUDIO_SECOND", 0.0)
    await voice_log_service.record_audio_usage(
        user_id=7, company_id=1, role_id=2, audio_seconds=30.0)
    assert usage_calls == []


async def test_usage_is_charged_once_a_multiplier_is_set(usage_calls, monkeypatch):
    monkeypatch.setattr(voice_log_service, "VOICE_TOKENS_PER_AUDIO_SECOND", 25.0)
    await voice_log_service.record_audio_usage(
        user_id=7, company_id=1, role_id=2, audio_seconds=4.0)
    assert len(usage_calls) == 1
    assert usage_calls[0]["total_tokens"] == 100


async def test_conversation_id_is_never_passed(usage_calls, monkeypatch):
    """token_usage_logs.conversation_id is a REAL FK. An id that is not yet
    persisted raises IntegrityError, which record_usage swallows into a
    rollback — losing the usage row silently."""
    monkeypatch.setattr(voice_log_service, "VOICE_TOKENS_PER_AUDIO_SECOND", 25.0)
    await voice_log_service.record_audio_usage(
        user_id=7, company_id=1, role_id=2, audio_seconds=2.0)
    assert usage_calls[0]["conversation_id"] is None


async def test_provider_is_hardcoded_to_race(usage_calls, monkeypatch):
    """Transcription always goes to RACE regardless of which provider serves
    chat. Copying the usual pattern would label every STT row 'openai'."""
    monkeypatch.setattr(voice_log_service, "VOICE_TOKENS_PER_AUDIO_SECOND", 25.0)
    await voice_log_service.record_audio_usage(
        user_id=7, company_id=1, role_id=2, audio_seconds=2.0)
    assert usage_calls[0]["provider"] == "race"
    assert usage_calls[0]["source"] == "stt"


async def test_usage_is_always_flagged_estimated(usage_calls, monkeypatch):
    """seconds -> tokens is a policy conversion, not a measurement."""
    monkeypatch.setattr(voice_log_service, "VOICE_TOKENS_PER_AUDIO_SECOND", 25.0)
    await voice_log_service.record_audio_usage(
        user_id=7, company_id=1, role_id=2, audio_seconds=2.0)
    assert usage_calls[0]["is_estimated"] is True


async def test_metering_failure_never_raises(monkeypatch):
    monkeypatch.setattr(voice_log_service, "VOICE_TOKENS_PER_AUDIO_SECOND", 25.0)

    def boom():
        raise RuntimeError("no database")

    monkeypatch.setattr(voice_log_service, "SessionLocal", boom)
    await voice_log_service.record_audio_usage(
        user_id=7, company_id=1, role_id=2, audio_seconds=2.0)  # must not raise


# ── What reaches the log file ────────────────────────────────────────────────

async def test_the_request_log_line_carries_no_transcript_and_no_filename(caplog):
    """Transcript text is personal data; the client filename is a CRLF
    log-injection vector. Neither belongs in the structured line."""
    import routers.voice as voice_router

    with caplog.at_level(logging.INFO):
        voice_router._log_line(
            "req123", 7, 2048, "audio/webm", "webm", 3.2,
            {"preprocess_ms": 10, "asr_ms": 200, "total_ms": 250},
            "en", 27, "whisperx_segments", "ok",
        )

    line = caplog.text
    assert "req123" in line and "audio/webm" in line and "whisperx_segments" in line
    assert "apply casual leave" not in line
    assert ".webm\n" not in line
    assert "\r" not in line
