"""Module to check for and download CDM files."""

import os
import sys
import yaml
import requests

CONFIG_PATH = os.path.join(os.getcwd(), "configs", "config.yaml")


def load_config():
    """Load the config file."""
    with open(CONFIG_PATH, "r", encoding="utf-8") as file:
        return yaml.safe_load(file)


def save_config(config):
    """Save the config file."""
    with open(CONFIG_PATH, "w", encoding="utf-8") as file:
        yaml.dump(config, file)


def prompt_yes_no(message):
    """Prompt the user for a yes or no answer."""
    answer = " "
    while answer[0].upper() not in ["Y", "N"]:
        answer = input(message)
    return answer[0].upper() == "Y"


def check_for_cdm(config_key, file_ext, download_url, cdm_dir, cdm_name):
    """Check for a CDM file."""
    config = load_config()
    cdm_value = config.get(config_key, "")
    cdm_dir_path = os.path.join(os.getcwd(), "configs", "CDMs", cdm_dir)
    os.makedirs(cdm_dir_path, exist_ok=True)

    if not cdm_value:
        if prompt_yes_no(
            f"No default {cdm_name} CDM specified, would you like to download one "
            "from The CDM Project? (Y)es / (N)o: "
        ):
            response = requests.get(download_url, timeout=10)
            if response.status_code == 200:
                file_path = os.path.join(cdm_dir_path, f"public.{file_ext}")
                with open(file_path, "wb") as file:
                    file.write(response.content)
                config[config_key] = "public"
                save_config(config)
                print(f"Successfully downloaded {cdm_name} CDM")
            else:
                sys.exit(
                    f"Download failed, please try again, or place a .{file_ext} file "
                    f"in {cdm_dir_path} and specify the name in {CONFIG_PATH}"
                )
        else:
            sys.exit(
                f"Place a .{file_ext} file in {cdm_dir_path} and specify the name in {CONFIG_PATH}"
            )
    else:
        base_name = (
            cdm_value
            if cdm_value.endswith(f".{file_ext}")
            else f"{cdm_value}.{file_ext}"
        )
        file_path = os.path.join(cdm_dir_path, base_name)
        if os.path.exists(file_path):
            return
        # Prompt to download if file is missing, even if config has a value
        if prompt_yes_no(
            f"{cdm_name} CDM {base_name} does not exist in {cdm_dir_path}. Would you like to download it from The CDM Project? (Y)es/(N)o: "
        ):
            response = requests.get(download_url, timeout=10)
            if response.status_code == 200:
                with open(file_path, "wb") as file:
                    file.write(response.content)
                config[config_key] = base_name.replace(f".{file_ext}", "")
                save_config(config)
                print(f"Successfully downloaded {cdm_name} CDM")
            else:
                sys.exit(
                    f"Download failed, please try again, or place a .{file_ext} file "
                    f"in {cdm_dir_path} and specify the name in {CONFIG_PATH}"
                )
        else:
            sys.exit(
                f"Place a .{file_ext} file in {cdm_dir_path} and specify the name in {CONFIG_PATH}"
            )


def check_for_cdms():
    """Check for CDM files."""
    check_for_cdm(
        config_key="default_wv_cdm",
        file_ext="wvd",
        download_url="https://cdm-project.com/CDRM-Team/CDMs/raw/branch/main/Widevine/L3/public.wvd",
        cdm_dir="WV",
        cdm_name="Widevine",
    )
    check_for_cdm(
        config_key="default_pr_cdm",
        file_ext="prd",
        download_url="https://cdm-project.com/CDRM-Team/CDMs/raw/branch/main/Playready/SL2000/public.prd",
        cdm_dir="PR",
        cdm_name="PlayReady",
    )
