"""
Integration demo: ASR khutbah text processed through StreamingScanner.

Demonstrates how ijaza detects the ayah, corrects it, and replaces
inaccurate LLM/human translations with authoritative scholarly ones.
"""

from ijaza import StreamingScanner, StreamingScannerOptions
from ijaza.translations import TranslationProvider


# --- Simulated ASR output (2 chunks, as if from batched ASR) ---

ASR_CHUNK_1 = (
    "خليله أشهد أنّه بلغ الرسالة وأدى الأمانة ونصح للأمة "
    "ونصح للأمّة وكشف الله به الغمّة، وجاهد في سبيل الله حق جهاده حتّى آتاه اليقين."
)

ASR_CHUNK_2 = (
    "أما بعد يقول الله عز وجل: يا أيها الذين آمنوا "
    "اتقوا الله حق تقاته ولا تموتن إلا وأنتم مسلمون."
)


# --- Wrong translations (LLM-generated / inaccurate human translation) ---

WRONG_ENGLISH = (
    'O you who believe! Fear Allah as His due right [is to be feared]; '
    'and let not any party betray another party; '
    'and certainly Allâh is Ever Watchful over what you do.'
)

WRONG_GERMAN = (
    'O die ihr glaubt! Fürchtet Allah wie es Seine Furcht gebührt; '
    'und sterbt nicht anders als im Islam.'
)


def test_streaming_khutbah_with_translation_replacement():
    """
    Full pipeline demo:
    1. ASR chunks arrive in sequence
    2. StreamingScanner detects Quran verse (3:102) across chunks
    3. Authentic Uthmani text replaces the ASR-garbled version
    4. Authoritative translations (Sahih Intl + Bubenheim) replace wrong ones
    """
    provider = TranslationProvider()
    scanner = StreamingScanner(
        options=StreamingScannerOptions(
            overlap_words=15,
            min_confidence=0.80,
            asr_tolerant=True,
        ),
        translation_provider=provider,
    )

    # --- Process chunk 1 (no ayah expected yet, just khutbah intro) ---
    r1 = scanner.process_chunk(ASR_CHUNK_1)

    print("=" * 70)
    print("CHUNK 1 (khutbah intro)")
    print("=" * 70)
    print(f"Text: {ASR_CHUNK_1[:80]}...")
    print(f"Complete verses found: {len(r1.complete_verses)}")
    print(f"Partial verse pending: {r1.partial_verse is not None}")
    print()

    # --- Process chunk 2 (contains the ayah) ---
    r2 = scanner.process_chunk(ASR_CHUNK_2)

    print("=" * 70)
    print("CHUNK 2 (contains ayah)")
    print("=" * 70)
    print(f"Text: {ASR_CHUNK_2}")
    print(f"Complete verses found: {len(r2.complete_verses)}")
    print()

    # --- Flush remaining ---
    r_final = scanner.flush()

    # --- Collect all detected verses ---
    all_verses = r1.complete_verses + r2.complete_verses + r_final.complete_verses
    print("=" * 70)
    print(f"TOTAL VERSES DETECTED: {len(all_verses)}")
    print("=" * 70)

    assert len(all_verses) >= 1, "Should detect at least one Quranic verse"

    for v in all_verses:
        print(f"\n--- Detected Verse: {v.reference} ---")
        print(f"  ASR heard:     {v.original_text}")
        print(f"  Correct text:  {v.correct_text}")
        print(f"  Confidence:    {v.confidence:.2f}")
        print(f"  Needs fix:     {v.needs_correction}")

        # Show authoritative translations
        if v.translations.get('en'):
            print(f"\n  ENGLISH (Sahih International - authoritative):")
            print(f"    {v.translations['en']}")
        if v.translations.get('de'):
            print(f"\n  GERMAN (Bubenheim & Elyas - authoritative):")
            print(f"    {v.translations['de']}")

        # --- Compare with wrong translations ---
        print(f"\n  --- WRONG English (LLM/human, NOT authoritative) ---")
        print(f"    {WRONG_ENGLISH}")

        print(f"\n  --- WRONG German (LLM/human, NOT authoritative) ---")
        print(f"    {WRONG_GERMAN}")

        # Show the replacement
        if v.translations.get('en'):
            print(f"\n  >>> English REPLACED: wrong LLM translation")
            print(f"      FROM: \"{WRONG_ENGLISH[:60]}...\"")
            print(f"      TO:   \"{v.translations['en']}\"")

        if v.translations.get('de'):
            print(f"\n  >>> German REPLACED: wrong LLM translation")
            print(f"      FROM: \"{WRONG_GERMAN[:60]}...\"")
            print(f"      TO:   \"{v.translations['de']}\"")

    print()

    # --- Assertions ---
    verse = all_verses[0]
    assert '3:102' in verse.reference or any('3:102' in v.reference for v in all_verses), \
        f"Expected 3:102, got references: {[v.reference for v in all_verses]}"
    assert verse.translations.get('en'), "English translation should be present"
    assert verse.translations.get('de'), "German translation should be present"
    assert verse.translations['en'] != WRONG_ENGLISH, \
        "Authoritative translation should differ from wrong LLM translation"
