from pathlib import Path
import subprocess, json
from google import genai

ROOT = Path('/root/ya-video-factory')
PILOT = ROOT / 'pilots/T13'
line = (ROOT / '.env').read_text(encoding='utf-8').strip()
key = line.split('=', 1)[1].strip()
client = genai.Client(api_key=key)

scenes = {
    1: (3.0, 'Avant de partager un document, contrôlez sa version finale.'),
    2: (8.0, 'Ouvrez le devis enregistré. Pour voir la version destinée au client, choisissez Imprimer.'),
    3: (11.0, "L'aperçu montre la mise en page finale. Relisez toutes les pages. Vérifiez le nom du client, les travaux et les montants."),
    4: (2.0, ''),
    5: (12.0, 'Ici, nous contrôlons le devis D E V, deux mille vingt-six, zéro zéro quatorze pour Académie Client Villa. Le client, les lignes et les totaux doivent correspondre à la fiche YA Manager.'),
    6: (9.0, "Un P D F est un fichier prêt à conserver ou à envoyer sans changer sa mise en page. Téléchargez-le, ou imprimez le document, seulement après ce contrôle."),
    7: (3.0, 'Le document est maintenant prêt à être partagé.'),
}

for i, (target, text) in scenes.items():
    out = PILOT / 'audio' / f's{i}.wav'
    if not text:
        subprocess.run(['ffmpeg','-y','-f','lavfi','-i','anullsrc=r=24000:cl=mono','-t',str(target),'-c:a','pcm_s16le',str(out)],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
        continue
    response = client.models.generate_content(
        model='gemini-3.8-flash-lite-tts',
        contents=[{
            'role': 'user',
            'parts': [{
                'text': text,
                'speech_metadata': {
                    'style': 'voix française naturelle, professionnelle et rassurante, débit proche de 135 mots par minute, articulation claire'
                }
            }]
        }],
        config={
            'response_modalities': ['AUDIO'],
            'speech_config': {'voice_config': {'voice': 'Kore'}}
        }
    )
    raw = PILOT / 'audio' / f's{i}_raw.wav'
    raw.write_bytes(response.candidates[0].content.parts[0].inline_data.data)
    probe = json.loads(subprocess.check_output([
        'ffprobe','-v','error','-show_entries','format=duration','-of','json',str(raw)
    ]))
    duration = float(probe['format']['duration'])
    desired_voice = max(target - 0.25, 0.5)
    tempo = max(0.5, min(2.0, duration / desired_voice))
    if duration > desired_voice:
        audio_filter = f'atempo={tempo:.6f},apad=pad_dur={target}'
    else:
        audio_filter = f'apad=pad_dur={target}'
    subprocess.run([
        'ffmpeg','-y','-i',str(raw),'-af',audio_filter,'-t',str(target),
        '-ar','24000','-ac','1','-c:a','pcm_s16le',str(out)
    ],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    print(f'SCENE_{i}_AUDIO raw={duration:.3f}s target={target:.2f}s tempo={tempo:.3f}')

print('AUDIO_PASS')
