from helpers.signature_generator import *
from pyplayready.cdm import Cdm
from pyplayready.device import Device
from pyplayready.pssh import PSSH
import requests
import os
import json

def get_prd():
    device_dir = os.path.join(os.getcwd(), "device")
    
    # Collect all .prd files in the /device directory
    prd_files = [f for f in os.listdir(device_dir) if f.endswith(".prd")]

    # If no .prd files are found, raise an error
    if not prd_files:
        raise Exception("No .prd file found!")

    # If exactly one .prd file is found, return its full path
    if len(prd_files) == 1:
        return os.path.join(device_dir, prd_files[0])

    # If multiple .prd files are found, prompt the user to select one
    print("Multiple .prd files found:")
    for file in prd_files:
        print(f" - {file}")

    while True:
        choice = input("Please select a .prd file by name (including .prd extension): ").strip()
        if choice in prd_files:
            return os.path.join(device_dir, choice)
        print("Invalid choice! Please try again.")

def decrypt(lic_url, pssh, proxies):
    pssh = PSSH(pssh)

    prd_path = get_prd()
    #print("Using PRD file:", prd_path)
    #print("File size (bytes):", os.path.getsize(prd_path))

    # Just pass the path directly to Device.load()
    device = Device.load(prd_path)

    cdm = Cdm.from_device(device)
    challenge = cdm.get_license_challenge(pssh.wrm_headers[0])

    headers = {
        'Origin': 'https://www.nowtv.com',
        'Referer': 'https://www.nowtv.com/',
        'Content-Type': 'text/xml; charset=UTF-8'
    }

    licence = requests.post(lic_url, headers=headers, data=challenge, proxies=proxies)

    try:
        licence.raise_for_status()
        if licence.status_code != 200:
            #print("License server returned non-200 status:")
            #print(licence.content)
            exit(1)

        cdm.parse_license(licence.text)

        keys = []
        for key in cdm.get_keys():
            keys.append(f"{key.key_id.hex}:{key.key.hex()}")
        #print("Decryption keys:", keys)
        return keys

    except Exception as e:
        #print('License request failed')
        #print(licence.content)
        raise e