"""Tests for Langfuse client initialization and error mapping."""

from __future__ import annotations

import pytest

from dr_langfuse.client import LangfuseConfig
from dr_langfuse.errors.codes import ErrorCode
from dr_langfuse.errors.langfuse_error import LangfuseError
from dr_langfuse.prompts.langfuse_prompt_provider import LangfusePromptProvider
from dr_langfuse.prompts.prompt_fetch_request import PromptFetchRequest
from dr_langfuse.tracing.emitter import LangfuseTraceEmitter
from dr_langfuse.tracing.models import TraceEventRequest


def test_client_init_missing_credentials_maps_to_auth() -> None:
    provider = LangfusePromptProvider(config=LangfuseConfig())
    emitter = LangfuseTraceEmitter(config=LangfuseConfig())

    with pytest.raises(LangfuseError) as exc_info:
        provider.fetch_prompt(PromptFetchRequest(prompt_name="x"))

    assert exc_info.value.error.code == ErrorCode.AUTH

    ack = emitter.emit_trace(TraceEventRequest(event_name="runtime.step"))
    assert ack.accepted is False
    assert ack.error is not None
    assert ack.error.code == ErrorCode.AUTH


def test_client_init_value_error_without_auth_tokens_maps_to_malformed_request() -> (
    None
):
    def _bad_config_factory(config: LangfuseConfig) -> None:
        del config
        raise ValueError("invalid host url")

    provider = LangfusePromptProvider(client_factory=_bad_config_factory)

    with pytest.raises(LangfuseError) as exc_info:
        provider.fetch_prompt(PromptFetchRequest(prompt_name="x"))

    assert exc_info.value.error.code == ErrorCode.MALFORMED_REQUEST


def test_client_init_value_error_with_author_text_stays_malformed_request() -> None:
    def _bad_config_factory(config: LangfuseConfig) -> None:
        del config
        raise ValueError("author field missing")

    provider = LangfusePromptProvider(client_factory=_bad_config_factory)

    with pytest.raises(LangfuseError) as exc_info:
        provider.fetch_prompt(PromptFetchRequest(prompt_name="x"))

    assert exc_info.value.error.code == ErrorCode.MALFORMED_REQUEST
