"""Shared test fixtures for Gherbal tests."""

import os
import json
import tempfile
import pytest
import pandas as pd


@pytest.fixture
def sample_texts():
    """Sample texts in various languages for testing."""
    return {
        "eng_Latn": "The quick brown fox jumps over the lazy dog",
        "fra_Latn": "Bonjour le monde comment allez vous",
        "arb_Arab": "مرحبا بالعالم كيف حالكم اليوم",
        "deu_Latn": "Guten Morgen wie geht es Ihnen heute",
        "spa_Latn": "Buenos dias como estas hoy amigo",
        "kor_Hang": "안녕하세요 오늘 날씨가 좋네요",
        "jpn_Jpan": "今日はとても良い天気ですね",
        "zho_Hans": "今天天气真好你好吗",
        "hin_Deva": "नमस्ते आज मौसम बहुत अच्छा है",
        "rus_Cyrl": "Доброе утро как дела сегодня",
    }


@pytest.fixture
def noisy_texts():
    """Texts with noise (URLs, mentions, emojis, etc.)."""
    return [
        "Hello @user123 check https://example.com #cool",
        "@mention this is a test @@doublemention",
        "🎉🎊 Great news everyone! 🎈",
        "Mixed 123 numbers and text",
        "   extra   spaces   everywhere   ",
        "",
        "12345",
        "مرحبا @user بالعالم https://test.com",
    ]


@pytest.fixture
def train_df():
    """Small training DataFrame for testing."""
    data = []
    for lang, texts in [
        ("eng_Latn", [
            "the cat sat on the mat",
            "good morning how are you today",
            "the weather is nice and sunny",
            "please pass me the butter knife",
            "reading books is a great hobby",
            "what time does the train leave",
            "the museum closes at five pm",
            "she plays piano very beautifully",
            "we went to the park yesterday",
            "the flowers bloom in springtime",
        ]),
        ("fra_Latn", [
            "le chat est assis sur le tapis",
            "bonjour comment allez vous aujourd hui",
            "il fait beau et ensoleille dehors",
            "je voudrais un cafe au lait svp",
            "la lecture est un bon passe temps",
            "a quelle heure part le train demain",
            "le musee ferme a cinq heures soir",
            "elle joue tres bien du piano fort",
            "nous sommes alles au parc hier midi",
            "les fleurs poussent au printemps beau",
        ]),
        ("arb_Arab", [
            "القطة جلست على السجادة الكبيرة",
            "صباح الخير كيف حالكم اليوم",
            "الطقس جميل ومشمس في الخارج",
            "اريد قهوة بالحليب من فضلك",
            "القراءة هواية رائعة ومفيدة جدا",
            "في اي ساعة يغادر القطار غدا",
            "يغلق المتحف في الساعة الخامسة",
            "تعزف البيانو بشكل جميل جدا",
            "ذهبنا الى الحديقة بالامس مع الاطفال",
            "الازهار تتفتح في فصل الربيع",
        ]),
    ]:
        for text in texts:
            data.append({"lang": lang, "text": text})

    return pd.DataFrame(data)


@pytest.fixture
def eval_df(train_df):
    """Small evaluation DataFrame (reuses a subset of train data for testing)."""
    return train_df.groupby("lang").head(3).reset_index(drop=True)


@pytest.fixture
def tmp_dir():
    """Temporary directory for model saving/loading tests."""
    with tempfile.TemporaryDirectory() as d:
        yield d


@pytest.fixture
def mock_model_dir(tmp_dir):
    """
    Create a mock model directory with labels.txt and a minimal config.json.
    Note: No actual .ftz/.bin file — tests that need a real model should
    use the trained_model fixture instead.
    """
    labels = ["eng_Latn", "fra_Latn", "arb_Arab"]
    with open(os.path.join(tmp_dir, "labels.txt"), "w") as f:
        for label in labels:
            f.write(f"{label}\n")

    config = {
        "model_type": "gherbal",
        "fasttext_path": "model.ftz",
        "labels_path": "labels.txt",
        "auto_map": {
            "AutoModel": "gherbal_model.Gherbal",
            "AutoConfig": "gherbal_config.GherbalConfig",
        },
    }
    with open(os.path.join(tmp_dir, "config.json"), "w") as f:
        json.dump(config, f)

    return tmp_dir


@pytest.fixture(scope="session")
def trained_model(tmp_path_factory):
    """
    Train a small model once per test session (expensive fixture).
    Returns (model, model_dir).
    """
    from gherbal import Gherbal

    model_dir = str(tmp_path_factory.mktemp("trained_model"))

    data = []
    for lang, texts in [
        ("eng_Latn", [
            "the cat sat on the mat today",
            "good morning how are you doing",
            "the weather is nice and sunny today",
            "please pass me the butter and knife",
            "reading books is a great hobby really",
            "what time does the next train leave",
            "the museum closes at five in evening",
            "she plays piano very beautifully well",
            "we went to the green park yesterday",
            "the flowers bloom beautifully in spring",
            "hello world this is a great day",
            "i like to eat apples and bananas",
            "the river flows gently through valley",
            "she runs every morning in the park",
            "the sunset was beautiful last evening",
        ]),
        ("fra_Latn", [
            "le chat dort sur le grand tapis",
            "bonjour comment allez vous ce matin",
            "il fait tres beau et ensoleille dehors",
            "je voudrais un grand cafe au lait",
            "la lecture est un excellent passe temps",
            "a quelle heure le train part demain",
            "le vieux musee ferme a cinq heures",
            "elle joue du piano magnifiquement bien",
            "nous sommes partis au parc hier matin",
            "les belles fleurs poussent au printemps",
            "salut tout le monde comment ca va",
            "je mange des pommes et des bananes",
            "la riviere coule doucement dans la vallee",
            "elle court chaque matin dans le parc",
            "le coucher de soleil etait tres beau",
        ]),
        ("arb_Arab", [
            "القطة تنام على السجادة الكبيرة اليوم",
            "صباح الخير كيف حالكم جميعا اليوم",
            "الطقس رائع ومشمس في الخارج اليوم",
            "اريد فنجان قهوة بالحليب من فضلك",
            "القراءة هواية رائعة ومفيدة للجميع",
            "متى يغادر القطار القادم من المحطة",
            "المتحف القديم يغلق في الساعة الخامسة",
            "هي تعزف البيانو بشكل رائع وجميل",
            "ذهبنا جميعا الى الحديقة الكبيرة بالامس",
            "الازهار الجميلة تتفتح في فصل الربيع",
            "مرحبا بالعالم كيف حال الجميع اليوم",
            "احب اكل التفاح والموز كل يوم",
            "النهر يجري بهدوء عبر الوادي الاخضر",
            "تجري كل صباح في الحديقة العامة",
            "غروب الشمس كان جميلا جدا البارحة",
        ]),
    ]:
        for text in texts:
            data.append({"lang": lang, "text": text})

    df = pd.DataFrame(data)
    model = Gherbal.train(df, model_dir, train_opts={"epoch": 5, "dim": 50})

    return model, model_dir
