import pytest

from app.services.translation.config import AllergenConfig, TranslationServiceConfig
from app.services.translation.models.requests import TranslationRequest
from app.services.translation.service import TranslationService
from app.services.translation import service as service_module


def _build_config() -> TranslationServiceConfig:
    return TranslationServiceConfig(
        openai_api_key="test-key",
        translation_model="gpt-4o-mini",
        allergen_model="gpt-4o-mini",
        supported_languages=["bg", "de", "fr", "it"],
        allergens=[AllergenConfig(number=1, name="Milk")],
    )


@pytest.mark.anyio("asyncio")
async def test_translate_single_item_emits_analytics_only_for_primary_call(monkeypatch):
    analytics_contexts = []

    async def fake_json_completion(**kwargs):
        analytics_contexts.append(kwargs.get("analytics_context"))
        operation_id = kwargs["operation_id"]
        if operation_id == "allergens_only":
            return {"allergens": [1]}, {"total_tokens": 1}
        if operation_id == "single_item_english":
            return {
                "menuItemTranslation": "Salad",
                "descriptionTranslation": "Fresh salad",
            }, {"total_tokens": 1}
        return {
            "menuItemTranslations": {"bg": "salata", "de": "salat", "fr": "salade", "it": "insalata"},
            "descriptionTranslations": {"bg": "pryasna", "de": "frisch", "fr": "fraiche", "it": "fresca"},
        }, {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2, "model": "gpt-4o-mini"}

    monkeypatch.setattr(service_module.openai_client, "json_completion", fake_json_completion)

    service = TranslationService(_build_config())
    response, analytics_payload = await service.translate_single_item(
        TranslationRequest(
            menuItem="Salad",
            description="Fresh salad",
            englishIncluded=True,
            city="sofia",
            zavedenia_id=3054,
        )
    )

    assert response.allergens == [1]
    assert len(analytics_contexts) == 3
    assert sum(context.get("enabled", True) for context in analytics_contexts) == 0
    assert analytics_contexts[0]["enabled"] is False
    assert analytics_contexts[1]["enabled"] is False
    assert analytics_contexts[2]["enabled"] is False
    assert analytics_payload["service"] == "translation"
    assert analytics_payload["parsed_result"]["allergens"] == [1]


@pytest.mark.anyio("asyncio")
async def test_translate_batch_item_emits_analytics_only_for_primary_call(monkeypatch):
    analytics_contexts = []

    async def fake_json_completion(**kwargs):
        analytics_contexts.append(kwargs.get("analytics_context"))
        operation_id = kwargs["operation_id"]
        if operation_id == "batch_allergens_7":
            return {"allergens": [1]}, {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2, "model": "gpt-4o-mini"}
        if operation_id == "english_translation_batch_7":
            return {
                "menuItemTranslation": "Soup",
                "descriptionTranslation": "Hot soup",
            }, {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2, "model": "gpt-4o-mini"}
        return {
            "menuItemTranslations": {"bg": "supa", "de": "suppe"},
            "descriptionTranslations": {"bg": "goryashta", "de": "heiss"},
        }, {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2, "model": "gpt-4o-mini"}

    monkeypatch.setattr(service_module.openai_client, "json_completion", fake_json_completion)

    service = TranslationService(_build_config())
    result, _ = await service.translate_batch_item(
        language_from="bg",
        item={"id": 7, "name": "Soup", "description": "Hot soup"},
        english_included=True,
        city="sofia",
        zavedenia_id=3054,
    )

    assert result["allergens"] == [1]
    assert len(analytics_contexts) == 4
    assert sum(context.get("enabled", True) for context in analytics_contexts) == 0
    assert analytics_contexts[0]["enabled"] is False
    assert analytics_contexts[1]["enabled"] is False
    assert analytics_contexts[2]["enabled"] is False
    assert analytics_contexts[3]["enabled"] is False


@pytest.mark.anyio("asyncio")
async def test_translate_batch_logs_analytics_once_after_success(monkeypatch):
    async def fake_translate_batch_item(*args, **kwargs):
        return (
            {
                "id": 7,
                "menuItemTranslations": "<!-- start bg -->supa<!-- end bg -->",
                "descriptionTranslations": "<!-- start bg -->goryashta<!-- end bg -->",
                "allergens": [1],
            },
            [{"input_tokens": 2, "output_tokens": 3, "total_tokens": 5, "model": "gpt-4o-mini"}],
        )

    monkeypatch.setattr(TranslationService, "translate_batch_item", fake_translate_batch_item)

    service = TranslationService(_build_config())
    request = type(
        "BatchRequest",
        (),
        {
            "language_from": "bg",
            "menu_items": [type("Item", (), {"id": 7, "name": "Soup", "description": "Hot soup"})()],
            "type": None,
            "allergensOnly": None,
            "englishIncluded": False,
            "city": "sofia",
            "zavedenia_id": 3054,
            "model_dump": lambda self, exclude_none=True: {
                "language_from": "bg",
                "menu_items": [{"id": 7, "name": "Soup", "description": "Hot soup"}],
                "city": "sofia",
                "zavedenia_id": 3054,
            },
        },
    )()

    response, analytics_payload = await service.translate_batch(request)

    assert len(response.items) == 1
    assert analytics_payload["service"] == "translation"
    assert analytics_payload["parsed_result"]["items"][0]["id"] == 7
