"""
Test script: compare Gemini 2.5 Flash transcription for Darija/French audio.

This is a standalone test tool — not part of the active pipeline.

Usage:
    cd C:\\Dev\\Talk2CV\\backend
    .\\venv\\Scripts\\activate
    python scripts/test_gemini_transcribe.py <path_to_audio_file>

Requires GEMINI_API_KEY in backend/.env
"""

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from dotenv import load_dotenv
import os

BACKEND_ROOT = Path(__file__).resolve().parent.parent
load_dotenv(BACKEND_ROOT / ".env")

SYSTEM_PROMPT = (
    "You are an audio transcriber. Transcribe the audio exactly as spoken. "
    "Rules:\n"
    "- The speaker is Moroccan, speaking Darija mixed with French.\n"
    "- Transcribe Darija phonetically in LATIN script, never in Arabic script.\n"
    "- If French words are spoken, keep them in French as spoken.\n"
    "- Do not translate anything. Do not add content not present in the audio.\n"
    "- If unclear, transcribe your best guess rather than omitting."
)


def transcribe_with_gemini(audio_path: str) -> str:
    try:
        from google import genai
        from google.genai import types
    except ImportError:
        raise RuntimeError(
            "Package 'google-genai' is not installed. "
            "Run: pip install google-genai"
        )

    api_key = os.getenv("GEMINI_API_KEY", "")
    if not api_key:
        raise RuntimeError(
            "GEMINI_API_KEY is not set. Add it to backend/.env"
        )

    client = genai.Client(api_key=api_key)

    audio_file = Path(audio_path)
    if not audio_file.exists():
        raise FileNotFoundError(f"Audio file not found: {audio_path}")

    print(f"Uploading {audio_file.name} to Gemini Files API...")
    uploaded = client.files.upload(file=str(audio_file))
    print(f"Upload complete: {uploaded.name}")

    response = client.models.generate_content(
        model="gemini-2.5-flash",
        contents=[uploaded, SYSTEM_PROMPT],
    )
    return response.text


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python scripts/test_gemini_transcribe.py <path_to_audio>")
        sys.exit(1)

    audio_path = sys.argv[1]

    try:
        transcript = transcribe_with_gemini(audio_path)
        print("\n=== Gemini 2.5 Flash Transcript ===")
        print(transcript)
    except FileNotFoundError as e:
        print(f"ERROR: {e}")
        sys.exit(1)
    except RuntimeError as e:
        print(f"ERROR: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"ERROR: Unexpected error during transcription: {e}")
        sys.exit(1)
