import os
from time import sleep
import webbrowser
import pyautogui
from optimisewait import optimiseWait
import smartpaste

def upload_youtube(filepath: str, title: str, image_path: str = None, description: str = None, channelurl: str = 'https://studio.youtube.com/', thumbnail: str = None, tags: str = None):
    """
    Automates uploading a video to YouTube.
    Args:
        filepath (str): The absolute path to the video file.
        title (str): The title of the YouTube video.
        image_path (str, optional): The path to the folder containing reference images for automation. Defaults to bundled 'uploadyt' folder.
        description (str, optional): The video description. Defaults to None.
        channelurl (str, optional): The YouTube Studio URL. Defaults to 'https://studio.youtube.com/'.
        thumbnail (str, optional): The absolute path to the thumbnail image. Defaults to None.
        tags (str, optional): A comma-separated string of tags. Defaults to None.
    """
    if image_path is None:
        image_path = os.path.join(os.path.dirname(__file__), 'uploadyt')

    webbrowser.open(channelurl)

    optimiseWait(['create','create2'], autopath=image_path)
    optimiseWait(['uploadvids','uploadvids2'], autopath=image_path)
    optimiseWait(['select','select2'], autopath=image_path)
    optimiseWait('filename', clicks=0, autopath=image_path)
    smartpaste.smartpaste(filepath)
    pyautogui.press('enter')
    optimiseWait('title', yoff=10, clicks=0, autopath=image_path)
    pyautogui.hotkey('ctrl', 'a')

    smartpaste.smartpaste(title)
    if thumbnail:
        optimiseWait(['thumbnail','thumbnail2'], autopath=image_path)
        optimiseWait('filename', clicks=0, autopath=image_path)
        smartpaste.smartpaste(thumbnail)
        pyautogui.press('enter')
    sleep(1)
    if description:
        optimiseWait('tell', autopath=image_path)
        smartpaste.smartpaste(description)

    if tags:
        optimiseWait('showmore', scrolltofind='pagedown', autopath=image_path)
        optimiseWait('tags', scrolltofind='pagedown', autopath=image_path)
        smartpaste.smartpaste(tags)

    for i in range(0, 3):
        sleep(1)
        optimiseWait('next', autopath=image_path)

    optimiseWait('publish', autopath=image_path)
