"""Metadata/citation recipe with a hand-annotated multilingual corpus.
No embedding, language detection, semantic retrieval, translation or LLM is run.
The topic and market are supplied as already-qualified inputs.
"""
from dataclasses import dataclass, replace


@dataclass(frozen=True)
class Passage:
    id: str
    topic: str
    market: str
    language: str
    current: bool
    role: str
    fact: str  # Human annotation, not a fact extracted by a model.
    text: str


CORPUS = [
    Passage('FR-CLOSE-v1-fr', 'closure', 'FR', 'fr', False, 'support', '72 h',
            'Ancienne procédure France : clôturer après 72 heures sans réponse.'),
    Passage('FR-CLOSE-v2-de', 'closure', 'FR', 'de', True, 'support', '48 h',
            'Französischer Support: Das Ticket nach 48 Stunden ohne Antwort schließen.'),
    Passage('DE-CLOSE-v2-fr', 'closure', 'DE', 'fr', True, 'support', '24 h',
            'Support allemand : clôturer le ticket après 24 heures sans réponse.'),
    Passage('FR-EXPORT-v3-en', 'export', 'FR', 'en', True, 'support', ';',
            'For the French support export, use a semicolon as the column separator.'),
]


def select(topic, market, query_language, role='support', same_language=False, corpus=CORPUS):
    if market is None:
        return ('clarify-market', None)
    eligible = [d for d in corpus if d.topic == topic and d.market == market
                and d.current and d.role == role]
    if same_language:
        eligible = [d for d in eligible if d.language == query_language]
    if not eligible:
        return ('abstain', None)
    if len({d.fact for d in eligible}) > 1:
        return ('document-conflict', None)
    chosen = sorted(eligible, key=lambda d: (d.language != query_language, d.id))[0]
    return ('evidence', {'id': chosen.id, 'fact': chosen.fact,
                         'original': chosen.text, 'language': chosen.language})


def run():
    # Expected sources are annotated independently of the selection function.
    cases = [
        ('closure', 'FR', 'FR-CLOSE-v2-de', '48 h', {
            'fr': 'Quand clôturer un ticket du support français sans réponse ?',
            'en': 'When should French support close an unanswered ticket?',
            'de': 'Wann schließt der französische Support ein Ticket ohne Antwort?'}),
        ('closure', 'DE', 'DE-CLOSE-v2-fr', '24 h', {
            'fr': 'Quel délai de clôture pour le support allemand ?',
            'en': 'What is the closure delay for German support?',
            'de': 'Welche Schließfrist gilt für den deutschen Support?'}),
        ('export', 'FR', 'FR-EXPORT-v3-en', ';', {
            'fr': 'Quel séparateur utiliser pour l’export du support français ?',
            'en': 'Which separator is used for the French support export?',
            'de': 'Welches Trennzeichen nutzt der französische Support beim Export?'})]
    single = cross = 0
    for topic, market, expected_id, expected_fact, questions in cases:
        for language, question in questions.items():
            assert question
            status, evidence = select(topic, market, language)
            assert status == 'evidence'
            assert evidence['id'] == expected_id and evidence['fact'] == expected_fact
            cross += 1
            single += select(topic, market, language, same_language=True)[0] == 'evidence'
    assert (single, cross) == (3, 9)
    assert select('closure', None, 'fr') == ('clarify-market', None)
    assert select('closure', 'FR', 'fr', role='visitor') == ('abstain', None)
    assert select('unknown-topic', 'FR', 'fr') == ('abstain', None)
    conflict = CORPUS + [replace(CORPUS[1], id='FR-CLOSE-v2-en', language='en', fact='72 h',
                               text='French support: close after 72 hours without a response.')]
    assert select('closure', 'FR', 'fr', corpus=conflict) == ('document-conflict', None)
    # Deliberately wrong witness: language is used as a substitute for market.
    wrong = [d for d in CORPUS if d.current and d.topic == 'closure' and d.language == 'fr'][0]
    assert wrong.market == 'DE' and wrong.fact == '24 h'
    print('PASS: 9 language/market/topic combinations; eligible source preserved in 9/9, versus 3/9 with a same-language restriction. Four exception cases: missing market, denied role, missing evidence, contradictory translation. Wrong language-as-market witness selects 24 h instead of 48 h. These are metadata tests, NOT model or retrieval benchmarks.')


if __name__ == '__main__':
    run()
