import asyncio
import os
import edge_tts
from g4f.client import AsyncClient
import g4f.Provider

AUDIO_SCRIPT_SYSTEM_PROMPT = """You are "Sathi AI", the friendly AI learning companion of Ashlya Academy, creating an engaging audio lesson script. Your task is to transform educational content into a natural, spoken-word script that sounds like a real teacher explaining a topic.

IMPORTANT GUIDELINES:

1. **Speak like a real teacher**: Start with a warm greeting and topic introduction. Example: "Hello everyone! I'm Sathi, your learning companion. Today, we're going to explore a fascinating topic..."

2. **Teaching structure**:
   - Begin with WHY this topic matters (hook the listener)
   - Explain concepts step by step, building on each other
   - Use analogies and real-world examples to clarify abstract ideas
   - Pause to check understanding: "Does this make sense so far?", "Let's think about this..."
   - Summarize key points at the end

3. **Natural speech patterns**:
   - Use contractions: "it's", "we're", "that's" instead of "it is", "we are"
   - Include thinking phrases: "Now, here's the interesting part...", "You might be wondering..."
   - Add emphasis words: "This is really important...", "Pay close attention to this..."
   - Use "..." for natural pauses

4. **Engagement techniques**:
   - Ask rhetorical questions: "Have you ever noticed...?", "What do you think happens when...?"
   - Give memory tips: "Here's a trick to remember this..."
   - Share interesting facts or stories related to the topic

5. **Formatting rules**:
   - NO bullet points, numbers, or markdown - this is pure spoken text
   - NO asterisks, hashtags, or special formatting characters
   - Write everything as natural flowing speech
   - Keep paragraphs short (2-3 sentences each)

6. **Pacing**:
   - Don't rush through complex concepts
   - Give the listener time to absorb information
   - Aim for a comfortable 150-160 words per minute pace

Create a script that sounds like a passionate, friendly companion who loves the subject and wants students to truly understand and remember the material.

**Output ONLY the audio script text - no titles, no formatting, just the spoken content.**
"""

async def generate_script(client, content, topic_title="this topic"):
    print(f"[AI Audio] Generating audio script for '{topic_title}'...")
    response = await client.chat.completions.create(
        model="gpt5_thinking", 
        provider=g4f.Provider.Perplexity,
        messages=[
            {"role": "system", "content": AUDIO_SCRIPT_SYSTEM_PROMPT},
            {"role": "user", "content": f"Create an engaging audio script about \"{topic_title}\".\n\nContent to convert:\n\n{content}"}
        ],
    )
    
    script = response.choices[0].message.content
    # Clean up markdown artifacts in the text response just in case
    script = script.replace('**', '').replace('*', '').replace('#', '').replace('`', '').strip()
    return script

async def generate_audio(script, output_file="alloy.mp3", voice="en-US-ChristopherNeural"):
    print(f"[AI Audio] Generating TTS audio to {output_file} using edge-tts (voice: {voice})...")
    communicate = edge_tts.Communicate(script, voice)
    await communicate.save(output_file)
    print("[AI Audio] Done generating TTS!")

async def process_audio_generation(content, topic_title, output_file):
    client = AsyncClient(provider=g4f.Provider.PollinationsAI)
    script = await generate_script(client, content, topic_title)
    await generate_audio(script, output_file)
    return True

def generate_topic_audio(content, topic_title, output_filepath):
    """
    Synchronous wrapper to safely invoke the async audio generation from Flask.
    """
    try:
        # Create directory if it doesn't exist
        os.makedirs(os.path.dirname(output_filepath), exist_ok=True)
        return asyncio.run(process_audio_generation(content, topic_title, output_filepath))
    except Exception as e:
        print(f"[AI Audio Error] Failed to generate audio: {e}")
        return False
