"""
Test end-to-end darija : audio → Whisper → Llama → JSON structuré.

Teste chaque step avec un audio darija manuellement enregistré.

Lance avec :
    python -m tests.test_parser_with_audio
"""

import asyncio
import json
from pathlib import Path

from app.services.whisper_service import whisper_service
from app.services.parser_service import parser_service


# ============================================
# Cas de test darija — un par step
# ============================================

TEST_CASES = [
    {
        "audio_file": "darija_step1.ogg",
        "step": 1,
        "label": "🇲🇦 Step 1 — Profil & Objectif (Darija)",
    },
    {
        "audio_file": "darija_step2.ogg",
        "step": 2,
        "label": "🇲🇦 Step 2 — Formations (Darija)",
    },
    {
        "audio_file": "darija_step3.ogg",
        "step": 3,
        "label": "🇲🇦 Step 3 — Expériences (Darija)",
    },
    {
        "audio_file": "darija_step4.ogg",
        "step": 4,
        "label": "🇲🇦 Step 4 — Compétences (Darija)",
    },
]


async def run_pipeline(audio_file: str, step: int, label: str):
    """Lance le pipeline complet pour un audio + step."""

    audio_path = Path(__file__).parent / "samples" / audio_file

    if not audio_path.exists():
        print(f"❌ Fichier introuvable : {audio_path}")
        print(f"   Enregistre et place-le dans tests/samples/\n")
        return

    print("=" * 70)
    print(f"{label}")
    print("=" * 70)
    print(f"📂 Audio  : {audio_path.name} ({audio_path.stat().st_size} bytes)")
    print(f"📌 Step   : {step}")
    print()

    # === Étape 1 : Whisper ===
    print("🎤 [1/2] Transcription Whisper...")

    with open(audio_path, "rb") as f:
        audio_bytes = f.read()

    try:
        whisper_result = await whisper_service.transcribe(
            audio_bytes=audio_bytes,
            filename=audio_file,
        )
    except Exception as e:
        print(f"   ❌ Whisper failed : {e}\n")
        return

    print(f"   ⚡ Durée    : {whisper_result.duration_seconds}s")
    print(f"   🌍 Langue   : {whisper_result.detected_language}")
    print(f"   📝 Texte    :")
    print(f"      {whisper_result.transcript}")
    print()

    # === Étape 2 : Llama Parser ===
    print("🤖 [2/2] Parsing Llama...")

    try:
        parse_result = await parser_service.parse(
            transcript=whisper_result.transcript,
            step=step,
        )
    except Exception as e:
        print(f"   ❌ Parser failed : {e}\n")
        return

    print(f"   ⚡ Durée    : {parse_result.duration_seconds}s")
    print(f"   🤖 Modèle   : {parse_result.model}")
    print(f"   📦 JSON structuré :")
    print(json.dumps(parse_result.fields, indent=4, ensure_ascii=False))
    print()

    # === Résumé pipeline ===
    total = whisper_result.duration_seconds + parse_result.duration_seconds
    print(f"⏱️  Pipeline total : {round(total, 2)}s")
    print()


async def main():
    print()
    print("🚀 Test pipeline darija : Audio → Whisper → Llama → JSON")
    print(f"📊 {len(TEST_CASES)} cas de test (1 par step)")
    print()

    for case in TEST_CASES:
        await run_pipeline(
            audio_file=case["audio_file"],
            step=case["step"],
            label=case["label"],
        )

    print("=" * 70)
    print("✅ Tests terminés")
    print("=" * 70)
    print()
    print("👉 Vérifications manuelles :")
    print("   - Step 1 : Llama extrait UNIQUEMENT 'objective' (pas nom/email/tel)")
    print("   - Step 2 : Toutes les formations + années correctement extraites")
    print("   - Step 3 : Toutes les expériences avec position/company/dates")
    print("   - Step 4 : Skills normalisés en français")
    print()


if __name__ == "__main__":
    asyncio.run(main())