"""
Main pipeline orchestrator for the YtQGen process.
"""

import os

# Handle imports for both running from src and from parent directory
try:
    from audio_processor import download_youtube_audio
    from transcription import transcribe_audio
    from summarizer import summarize_text
    from questionnaire_generator import generate_questionnaire
    from pdf_generator import save_text_as_pdf
except ImportError:
    from .audio_processor import download_youtube_audio
    from .transcription import transcribe_audio
    from .summarizer import summarize_text
    from .questionnaire_generator import generate_questionnaire
    from .pdf_generator import save_text_as_pdf


def process_stream(video_url, output_pdf="questionnaire.pdf"):
    """
    Full pipeline to process a YouTube video and generate a questionnaire PDF.
    
    Args:
        video_url (str): YouTube video URL
        output_pdf (str): Output PDF filename
        
    Returns:
        str: Path to generated PDF file, or None if error occurred
    """
    audio_file_path = None
    
    try:
        print("Downloading audio from YouTube...")
        audio_file_path = download_youtube_audio(video_url)
        if not audio_file_path or not os.path.exists(audio_file_path):
            print("Error: Unable to download audio.")
            return None

        print("Transcribing audio...")
        transcription = transcribe_audio(audio_file_path)
        if not transcription:
            print("Error: Transcription failed.")
            return None

        print("Summarizing transcription...")
        summary = summarize_text(transcription)

        print("Generating questionnaire...")
        questionnaire = generate_questionnaire(summary)

        print("Converting questionnaire to PDF...")
        save_text_as_pdf(questionnaire, output_pdf)

        print(f"\nPDF generated: {output_pdf}")
        return output_pdf
    
    except Exception as e:
        print(f"Error in pipeline: {e}")
        return None
    
    finally:
        # Clean up temporary audio file
        if audio_file_path and os.path.exists(audio_file_path):
            try:
                os.remove(audio_file_path)
                print(f"Cleaned up temporary audio file: {audio_file_path}")
            except Exception as e:
                print(f"Warning: Could not delete temporary file {audio_file_path}: {e}")
