import webbrowser
import os

from pytube import YouTube
from openai import OpenAI

# Config
OPENAI_API_KEY = "<YOUR OPENAI KEY HERE>"
OPENAI_MODEL = "gpt-4-0125-preview"
SYSTEM_PROMPT = "You are summarise-GPT, trained to summarise long video transcriptions to great accuracy. Your summaries keep the most important and relevant information. You take the same point of view as the original script (for example, if it's a monologue, you should keep it first-person) and also the same mood. The next message will be the transcript, and you will answer with your summary, and nothing else. Good luck."
HTML_FILENAME = "video_summary.html"

# Set up the OpenAI client with your API key
client = OpenAI(api_key=OPENAI_API_KEY)


# 1 — Download the Audio
def download_video(video_url):
    youtube = YouTube(video_url)
    audio_stream = youtube.streams.filter(only_audio=True).first()
    return audio_stream.download()

# 2 - Transcribe the audio
def transcribe(path_to_audio):
    with open(path_to_audio, 'rb') as audio_file:
        transcript = client.audio.transcriptions.create(
            model="whisper-1",
            file=audio_file,
            response_format='text', # otherwise returns a json
        )
    return transcript

# 3 - Summarise using GPT-4
def call_gpt(system, prompt, temp=0.5):
    response = client.chat.completions.create(model=OPENAI_MODEL,
    messages=[
        {"role": "system", "content": system},
        {"role": "user",   "content": prompt}
    ],
    temperature=temp)
    return response.choices[0].message.content

# 4 - A nice page for reading
def create_summary_page(video_name, video_link, summary_text):
    paragraphs = summary_text.split('\n')
    summary_html = ''.join(f'<p>{line}</p>' if line else '<p>&nbsp;</p>' for line in paragraphs)
    html_content = f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{video_name}</title>
        <style>
            body {{
                font-family: 'Palatino, Times New Roman', serif;
                font-size: 18px;
                margin: 0;
                padding: 0;
                display: flex;
                flex-direction: column;
                align-items: center;
            }}
            .video-container {{
                width: 80%;
                position: relative;
                padding-bottom: 56.25%;
                height: 0;
            }}
            .video-container iframe {{
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
            }}
            .summary {{
                width: 80%;
                max-width: 700px;
                margin-top: 20px;
                text-align: justify;
            }}
        </style>
    </head>
    <body>
        <h1>{video_name}</h1>
        <div class="video-container">
            <iframe src="{video_link}" frameborder="0" allowfullscreen></iframe>
        </div>
        <div class="summary">
            <h2>Summary</h2>
            {summary_html}
        </div>
    </body>
    </html>
    """

    with open(HTML_FILENAME, 'w') as file:
        file.write(html_content)

    print(f"HTML page created successfully. If it doesn't open automatically, open {HTML_FILENAME}")

# Helper functions
def get_video_name(path):
    # Extract video name without full path or file extension
    return os.path.splitext(os.path.basename(path))[0]

def convert_to_embed_url(video_url):
    # Extract the video ID and create the embeddable URL
    video_id = video_url.split('watch?v=')[1]
    embed_url = f"https://www.youtube.com/embed/{video_id}"
    return embed_url


if __name__ == '__main__':
    video_url = input('Video URL: ')
    print('downloading video')
    path_to_audio = download_video(video_url)
    print('transcribing')
    text = transcribe(path_to_audio)
    os.remove(path_to_audio)  # Delete the audio file after use
    print('calling gpt')
    summary = call_gpt(SYSTEM_PROMPT, text)

    video_name = get_video_name(path_to_audio)
    embed_url = convert_to_embed_url(video_url)

    create_summary_page(video_name=video_name,
                        video_link=embed_url,
                        summary_text=summary
                        )
    webbrowser.open(HTML_FILENAME, new=2)
