import g4f
from g4f import Provider, client
import json
import os
from typing import Dict, List, Sequence, Any, Union

# Updated system prompt for JSON format podcast generation
SYSTEM_PROMPT = '''
You are a podcast script generator. Create a natural dialogue between two hosts discussing the given topic.

CRITICAL: You must respond ONLY with valid JSON in the exact format specified below. Do not include any text outside the JSON structure.

MOST IMPORTANT : EVERY ASPECT OF JSON STRUCTURE SHOULD BE PROPERLY FOLLOWED
Required JSON format:
{
    "title": "Podcast Title",
    "voice_assignments": {
        "HOST": "nova",
        "EXPERT": "onyx"
    },
    "segments": [
        {
            "speaker": "HOST",
            "text": "Hello world"
        },
        {
            "speaker": "EXPERT",
            "text": "Hello world"
        }
    ]
}

Content Guidelines:
1. Create 30-40 exchanges between HOST and EXPERT
2. Use educational, conversational tone  
3. Make the content engaging and informative
4. HOST should ask questions and guide the conversation
5. EXPERT should provide detailed explanations and insights

Podcast Style Instructions:
1. Opening: Begin with welcoming phrase "Hey everyone, welcome back"
2. Dialog Structure: Conversational back-and-forth with affirmations like "Right," "Exactly," "Absolutely"
3. Language: Informal, accessible, enthusiastic
4. Content: Introduce sources early, use analogies, break down complex ideas
5. Host Interaction: One asks, other explains, validate each other
6. Audience Engagement: Address listeners directly
7. Structure: Start broad, narrow down, summarize key points
8. Closing: "So as we wrap things up..." and "Until next time, keep exploring"

Segment Types:
- "speech": Dialogue with speaker, text, and emotion
- "sfx": Sound effects with description and duration
- "pause": Silent pauses with duration in seconds

Make it engaging, informative, and educational while maintaining the conversational podcast format.

REMEMBER: Output ONLY valid JSON. No markdown, no explanations, just the JSON structure.
'''



def generate_podcast_discussion(topic_prompt: str, image_paths):
    """
    Generate a podcast discussion script based on a prompt and optional images
    
    Args:
        topic_prompt: The main topic for the podcast discussion
        image_paths: Optional list of paths to images to include for context
        
    Returns:
        str: JSON string containing the podcast script, or None if generation failed
    """
    try:
        client = g4f.Client(provider=Provider.Blackbox)

        # Handle image processing if images are provided
        images = []
        if image_paths:
            for image_path in image_paths:
                try:
                    if os.path.exists(image_path):
                        with open(image_path, "rb") as img_file:
                            # Read the file content and determine extension
                            img_content = img_file.read()
                            # Get file extension
                            _, ext = os.path.splitext(image_path)
                            ext = ext.lower().lstrip('.')
                            if not ext:
                                ext = 'jpg'  # Default extension
                            images.append([img_content, f"image.{ext}"])
                    else:
                        print(f"Warning: Image file not found: {image_path}")
                except Exception as e:
                    print(f"Error processing image {image_path}: {e}")
                    # Continue with other images

        messages = [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": topic_prompt}
        ]

        # Create the chat completion with or without images
        if images:
            response = client.chat.completions.create(messages=messages, images=images)
        else:
            response = client.chat.completions.create(messages=messages)

        if not response or not hasattr(response, 'choices') or len(response.choices) == 0:
            print("No valid response received from the AI provider")
            return None

        content = response.choices[0].message.content
        if not content or not content.strip():
            print("Received empty content from the AI provider")
            return None

        # Try to parse JSON from the response
        try:
            # Clean up the response - sometimes it includes markdown code blocks
            if content.startswith("```json"):
                content = content[7:]
            if content.endswith("```"):
                content = content[:-3]
            content = content.strip()

            # Parse JSON to validate it
            podcast_data = json.loads(content)
            
            # Validate minimum required structure
            if "title" not in podcast_data or "segments" not in podcast_data:
                print("Generated JSON is missing required fields")
                return None
                
            print(f"Successfully generated podcast script with {len(podcast_data.get('segments', []))} segments")
            return json.dumps(podcast_data, indent=2)
        except json.JSONDecodeError as e:
            print(f"Error parsing JSON response: {e}")
            print(f"Raw response content: {content}")
            return None
    except Exception as e:
        print(f"Unexpected error in generate_podcast_discussion: {e}")
        return None

   
