import subprocess
import tkinter as tk
from tkinter import filedialog
import time
import random

def sanitize_windows_filename(name: str) -> str:
    return (
        name.replace("\\", "-")
            .replace("/", "-")
            .replace(":", "-")
            .replace("*", "-")
            .replace("?", "-")
            .replace('"', "-")
            .replace("<", "-")
            .replace(">", "-")
            .replace("|", " ~")
            .strip()
    )

def build_command(product_slug: str, module: str, filename_text: str,
                  category_id: str, post_id: str) -> list:
    safe_module = sanitize_windows_filename(module)
    safe_name = sanitize_windows_filename(filename_text)

    cookies_path = r'V:\INTERNET\TUTORIALS\ContentCreator.com\www.contentcreator.com_cookies.txt'
    output_path = fr'V:\INTERNET\TUTORIALS\ContentCreator.com\{product_slug}\{safe_module}\{safe_name}.%(ext)s'
    url = f'https://www.contentcreator.com/products/{product_slug}/categories/{category_id}/posts/{post_id}'

    return [
        "powershell", "-Command",
        f'yt-dlp --cookies "{cookies_path}" -o "{output_path}" {url}'
    ]

def run_batch(file_path: str):
    with open(file_path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            try:
                product_slug, module, filename_text, category_id, post_id = line.split(";")
            except ValueError:
                print(f"Skipping malformed line: {line}")
                continue

            cmd = build_command(product_slug.strip(), module.strip(),
                                filename_text.strip(), category_id.strip(), post_id.strip())
            print("\nRunning:", " ".join(cmd))
            subprocess.run(cmd)

            # Randomized throttle between 2 and 5 seconds
            delay = random.uniform(2, 5)
            print(f"Sleeping for {delay:.2f} seconds...")
            time.sleep(delay)

if __name__ == "__main__":
    print("YT-DLP Batch Runner\n")

    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename(
        title="Select jobs file",
        filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
    )

    if not file_path:
        print("No file selected. Exiting.")
    else:
        print(f"Selected file: {file_path}")
        run_batch(file_path)
        print("\nAll jobs processed.")
