import base64
import binascii
import json
import requests
from Cryptodome.Cipher import AES
from flask import Blueprint, request
from hashlib import md5
from urllib.parse import urlparse, parse_qs

yos512_bp = Blueprint('yos512', __name__)

@yos512_bp.route('/yos512')
def yos512playlist():

    channel = request.args.get('channel', 'asp1')

    def unpad(data):
        return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))]

    def bytes_to_key(data, salt, output=48):
        assert len(salt) == 8, len(salt)
        data += salt
        key = md5(data).digest()
        final_key = key
        while len(final_key) < output:
            key = md5(key + data).digest()
            final_key += key
        return final_key[:output]

    def decrypt(encrypted, passphrase):
        encrypted = base64.b64decode(encrypted)
        assert encrypted[0:8] == b"Salted__"
        salt = encrypted[8:16]
        key_iv = bytes_to_key(passphrase, salt, 32+16)
        key = key_iv[:32]
        iv = key_iv[32:]
        aes = AES.new(key, AES.MODE_CBC, iv)
        return unpad(aes.decrypt(encrypted[16:]))

    currentURL = f'https://embed.now.net.eu.org/p/mlive?id={channel}&type=m'

    def get_id_from_url(url):
        parsed_url = urlparse(url)
        query_params = parse_qs(parsed_url.query)
        return query_params.get("id", None)[0]

    id_value = get_id_from_url(currentURL)


    jsonUrl = f'https://dt.now.net.eu.org/you?id={id_value}'

    headers = {
        'Origin': 'https://embed.now.net.eu.org',
    }

    # Make the GET request
    response = requests.get(jsonUrl, headers=headers)
    json_data = response.json()

    # Decrypt the keys

    password = "R0FUQVVESVJJQU5KSU5H" # interesting fact: this hardcoded key is the base64 of 'GATAU DIRI ANJING' with no spaces. Please do not translate this from Singaporian.

    encrypted_bytes = base64.b64decode(f'{json_data['clearKeys']}==')
    encrypted_hex = binascii.unhexlify(encrypted_bytes)
    key = password.encode('utf-8')

    pt = decrypt(encrypted_hex, key)

    parsed_keys = json.loads(pt)
    key_object = {}

    for key_id, key_value in parsed_keys.items():
        key_entry = {"keyId": key_id, "key": key_value}
        key_object = key_entry

    keys = key_object

    print(json_data['source'])
    print(keys)

    print(f'#EXTM3U\n\n#KODIPROP:inputstream.adaptive.license_type=clearkey\n#KODIPROP:inputstream.adaptive.license_key={keys['keyId']}:{keys['key']}\n{json_data['source']}')
    return (f'#EXTM3U\n\n#KODIPROP:inputstream.adaptive.license_type=clearkey\n#KODIPROP:inputstream.adaptive.license_key={keys['keyId']}:{keys['key']}\n{json_data['source']}')