

import json
from re import L
import sys
import asyncio
import os
import shutil
from datetime import datetime

from .main import create_topic_prompt, generate_podcast_discussion
from .podcast import generate_podcast_from_json
from .video_gen import create_video_from_directories, ProgressCallback


def main_async(subject, context, specific_focus, language="English", progress_callback=None, job_id=None):
    """
    Transcript bata video generate garne main function
    
    Args:
        subject: Podcast ko topic
        context: Topic ko context information
        specific_focus: Focus garne specific areas
        language: Podcast ko language (default: "English")
        progress_callback: Progress track garne optional ProgressCallback
        job_id: File naming ra tracking ko lagi optional job ID
    
    Returns:
        Video filename or generation fail bhayo bhane None
    """
    # Progress callback chaina bhane default create garne
    if progress_callback is None:
        progress_callback = ProgressCallback()
    
    progress_callback.update(0, "Starting podcast generation")
    print("Starting podcast generation...")
    topic = create_topic_prompt(
        subject=subject,
        context=context,
        specific_focus=specific_focus
    )

    progress_callback.update(5, "Generating podcast discussion")
    print("Generating podcast discussion...")
    result = generate_podcast_discussion(topic, language)
    
    if result is None:
        progress_callback.update(0, "Failed to generate podcast content")
        print("ERROR: Failed to generate podcast content. Exiting.")
        return None
    
    try:
        progress_callback.update(10, "Converting podcast data to JSON")
        print("Converting podcast data to JSON...")
        json_string = json.dumps(result, indent=2)
        
        progress_callback.update(15, "Generating audio and images for each segment")
        print("Generating audio and images for each segment...")
        
        # Job ID cha bhane config ma setup garne
        output_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        podcast_output_dir = os.path.join(output_dir, "podcast_output")
        
        from .podcast import PodcastConfig, PodcastGenerator
        config = PodcastConfig(
            output_dir=podcast_output_dir,
            audio_dir=os.path.join(podcast_output_dir, "audio"),
            image_dir=os.path.join(podcast_output_dir, "images"),
            temp_audio_dir=os.path.join(podcast_output_dir, "temp_audio"),
            temp_image_dir=os.path.join(podcast_output_dir, "temp_images"),
            job_id=job_id
        )
        
        # Job ID bhako config sanga generator create garne
        generator = PodcastGenerator(config)
        combined_audio_path, metadata, segment_results = generator.generate_podcast_from_json(json_string)
        
        # Per segment progress increment calculate garne
        segment_count = len(segment_results)
        progress_per_segment = 30 / max(1, segment_count)  # audio/image generation ko lagi 30% progress
        
        # Segment anusar organize gareko file paths ko dictionary
        file_paths = {
            "combined_audio": combined_audio_path,
            "segments": []
        }
        
        # Har segment ko files dictionary ma add garne
        for i, segment in enumerate(segment_results):
            segment_data = {
                "index": segment["index"],
                "speaker": segment["speaker"],
                "audio_path": segment["audio_path"],
                "image_path": segment["image_path"]
            }
            file_paths["segments"].append(segment_data)
            
            # Process gareko har segment ko progress update garne
            progress_value = 15 + (i + 1) * progress_per_segment
            progress_callback.update(0, f"Processed segment {i+1}/{segment_count}")
        
        progress_callback.update(45, "Audio and image generation complete")
        print(f"\nPodcast generation complete!")
        print(f"Combined audio: {combined_audio_path}")
        print(f"Generated {len(file_paths['segments'])} segment files")
        
        # Generated files bata video create garne
        progress_callback.update(50, "Preparing for video creation")
        print("\nCreating final video...")
        
        # Properly named files ko lagi temporary directories create garne
        temp_image_dir = os.path.join(os.path.dirname(combined_audio_path), "temp_images")
        temp_audio_dir = os.path.join(os.path.dirname(combined_audio_path), "temp_audio")
        os.makedirs(temp_image_dir, exist_ok=True)
        os.makedirs(temp_audio_dir, exist_ok=True)
        
        # Video creation ko lagi files copy ani rename garne
        progress_callback.update(55, "Preparing media files")
        for i, segment in enumerate(file_paths["segments"]):
            if segment["image_path"] and segment["audio_path"]:
                # File extensions nikalne
                audio_ext = os.path.splitext(segment["audio_path"])[1]
                
                # Image path handle garne - None pani huna sakcha
                if segment["image_path"]:
                    image_ext = os.path.splitext(segment["image_path"])[1]
                else:
                    image_ext = ".jpg"  # Image chaina bhane default extension
                
                # Consistent names create garne
                segment_name = f"segment_{i+1:03d}"
                
                # Naya names sanga files copy garne
                temp_image_path = os.path.join(temp_image_dir, f"{segment_name}{image_ext}")
                temp_audio_path = os.path.join(temp_audio_dir, f"{segment_name}{audio_ext}")
                
                if segment["image_path"]:
                    shutil.copy2(segment["image_path"], temp_image_path)
                shutil.copy2(segment["audio_path"], temp_audio_path)
                
                print(f"Prepared segment {i+1} for video creation")
        
        # Output video file path generate garne
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        video_name = f"podcast_video_{timestamp}.mp4"
        video_output_path = os.path.join(os.path.dirname(combined_audio_path), f"{video_name}")
        
        # Transition type preference
        transition_type = 'crossfade'  # Default
        transition_duration = 1  # Default in seconds
        
        progress_callback.update(60, "Creating video with transitions")
        print(f"Creating video with {transition_type} transitions...")
        
        # Transitions sanga video create garne
        video = create_video_from_directories(
            temp_image_dir, 
            temp_audio_dir, 
            video_output_path,
            progress_callback=progress_callback,  # Progress callback pass garne
            job_id=job_id  # Files filter garna job_id pass garne
        )
        
        if video:
            progress_callback.update(95, "Video created successfully")
            print(f"Video created successfully: {video_output_path}")
            file_paths["video_path"] = video_output_path
            
            # Job ID cha bhane temporary files clean up garne
            if job_id:
                progress_callback.update(98, "Cleaning up temporary files")
                print(f"Cleaning up temporary files for job {job_id}...")
                # Generator lai afno files afai clean up garna dine
                generator.cleanup_job_files()
            
            progress_callback.complete()
            return video_name
        else:
            progress_callback.update(0, "Failed to create video")
            print("Failed to create video")
            return None
        
    except Exception as e:
        progress_callback.update(0, f"Error: {str(e)}")
        print(f"ERROR: Failed to process podcast: {e}")
        import traceback
        traceback.print_exc()
        return None

