import os
import json
import sys
from datetime import datetime

def generate_images_from_pdf(pdf_path):
    """
    Extract images from PDF using pdf2image if available
    """
    try:
        from pdf2image import convert_from_path
        
        # Convert PDF to images
        pages = convert_from_path(pdf_path, dpi=150)
        
        # Create output directory for images
        output_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "generated_media")
        os.makedirs(output_dir, exist_ok=True)
        
        image_paths = []
        for i, page in enumerate(pages):
            image_filename = f"pdf_page_{i+1}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
            image_path = os.path.join(output_dir, image_filename)
            page.save(image_path, 'JPEG')
            image_paths.append(image_path)
            
        return image_paths
        
    except ImportError:
        print("pdf2image not available, skipping image extraction")
        return []
    except Exception as e:
        print(f"Error extracting images from PDF: {e}")
        return []

def pdf_to_podcast(pdf_path, title=None, output_dir=None):
    """
    Convert a PDF to a podcast with images

    Args:
        pdf_path: Path to the PDF file
        title: Title for the podcast (optional)
        output_dir: Directory to save output files (optional)

    Returns:
        dict: Metadata about the generated podcast
    """
    # Generate images from PDF
    image_paths = generate_images_from_pdf(pdf_path)
    # print(f'image_paths: {image_paths}')

    # Convert absolute image paths to API URLs and copy images to generated_media
    api_image_urls = []

    # Add parent directory to path to import the script generator
    current_dir = os.path.dirname(os.path.abspath(__file__))
    if current_dir not in sys.path:
        sys.path.append(current_dir)

    from generate_script import generate_podcast_discussion

    # Generate a title if none provided
    if not title:
        title = f"PDF Podcast {datetime.now().strftime('%Y-%m-%d')}"

    # Create a prompt based on the PDF content and images
    prompt = f"Create an educational podcast discussing a PDF document titled '{title}' with {len(image_paths)} pages. The images show content from the document. Make it engaging and informative for listeners who want to understand this document."

    try:
        # Generate podcast script using the generator
        podcast_json = generate_podcast_discussion(prompt, image_paths)
        
        print(f'podcast_json type: {type(podcast_json)}')
        print(f'podcast_json: {podcast_json}')
        
        # Check if podcast_json is None or empty
        if not podcast_json:
            print("Warning: No podcast script generated, using fallback")
            raise ValueError("Empty or null response from generate_podcast_discussion")
            
        # Import here to avoid circular imports
        from .podcast import PodcastGenerator, PodcastConfig
    
        # Create podcast config
        if not output_dir:
            output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../generated_audio")
    
        config = PodcastConfig(output_dir=output_dir)
        podcast_generator = PodcastGenerator(config)
    
        # Generate the podcast audio from the dynamically generated script
        audio_path, podcast_metadata = podcast_generator.generate_podcast_from_json(podcast_json)
    
        # Add images to metadata
        podcast_metadata['images'] = api_image_urls
    
        # Add audio URL to metadata with correct API path
        podcast_metadata['audio_url'] = f"/api/audio_generation/audio/{os.path.basename(audio_path)}"
        
        print(f"Successfully generated podcast audio: {audio_path}")
        return podcast_metadata
    
    except (json.JSONDecodeError, ValueError, Exception) as e:
        print(f"Error processing podcast JSON: {e}")
        print("Using enhanced fallback script instead")
        
        # Enhanced fallback script with more content
        num_pages = len(image_paths)
        podcast_data = {
            "title": f"Audio Guide: {title}",
            "voice_assignments": {
                "HOST": "nova",
                "EXPERT": "onyx"
            },
            "segments": [
                {
                    "speaker": "HOST",
                    "text": f"Welcome to this audio guide for the document titled '{title}'. I'm your host, and I'll be walking you through this educational content."
                },
                {
                    "speaker": "EXPERT",
                    "text": f"Thank you for that introduction. This audio guide covers a {num_pages}-page document, and I'll be sharing key insights and explanations to help you understand the material."
                },
                {
                    "speaker": "HOST", 
                    "text": f"Perfect! Let's start with an overview. What should our listeners know about '{title}' right from the beginning?"
                },
                {
                    "speaker": "EXPERT",
                    "text": f"Great question! This document appears to contain important information that can benefit anyone interested in this topic. Let me break down the key concepts for our audience."
                },
                {
                    "speaker": "HOST",
                    "text": "That's very helpful. Can you elaborate on the main points covered in this document?"
                },
                {
                    "speaker": "EXPERT", 
                    "text": f"Absolutely. Based on the {num_pages} pages we've analyzed, this document covers several important areas. Each section builds upon the previous one to create a comprehensive understanding of the subject matter."
                },
                {
                    "speaker": "HOST",
                    "text": "Excellent! What would you say is the most important takeaway for our listeners?"
                },
                {
                    "speaker": "EXPERT",
                    "text": "The most crucial point is that this document provides valuable insights that can be applied in real-world situations. I'd encourage listeners to refer back to the original PDF for detailed diagrams, charts, and supplementary information."
                },
                {
                    "speaker": "HOST",
                    "text": "That's a great summary! Before we wrap up, are there any specific sections you'd recommend our audience to focus on?"
                },
                {
                    "speaker": "EXPERT",
                    "text": "I'd recommend paying special attention to the key concepts presented throughout the document. Each page contains valuable information that contributes to the overall understanding of the topic."
                },
                {
                    "speaker": "HOST",
                    "text": "Thank you for this insightful overview! Remember, listeners, this audio guide complements the original PDF document, so be sure to review the visual content as well."
                },
                {
                    "speaker": "EXPERT",
                    "text": "Exactly! This has been a great discussion, and I hope our listeners found this audio guide helpful for understanding the key concepts presented in the document."
                }
            ]
        }
        podcast_json = json.dumps(podcast_data)
        
        # Import here to avoid circular imports
        from .podcast import PodcastGenerator, PodcastConfig
    
        # Create podcast config
        if not output_dir:
            output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../generated_audio")
    
        config = PodcastConfig(output_dir=output_dir)
        podcast_generator = PodcastGenerator(config)
    
        # Generate the podcast audio from the fallback script
        audio_path, podcast_metadata = podcast_generator.generate_podcast_from_json(podcast_json)
    
        # Add images to metadata
        podcast_metadata['images'] = api_image_urls
    
        # Add audio URL to metadata with correct API path
        podcast_metadata['audio_url'] = f"/api/audio_generation/audio/{os.path.basename(audio_path)}"
        
        # Mark as fallback generated
        podcast_metadata['fallback_generated'] = True
        podcast_metadata['ai_script_generated'] = False
    
        print(f"Successfully generated fallback podcast audio: {audio_path}")
        return podcast_metadata
