#!/usr/bin/python3
import sys
import os
import base64
import json
import datetime
import pytz

# Add parent directory to path for o11 import
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import o11

from bs4 import BeautifulSoup
from pywidevine.cdm import Cdm
from pywidevine.device import Device
from pywidevine.pssh import PSSH

# Parse command line parameters
user = o11.parse_params(sys.argv, 'user')
password = o11.parse_params(sys.argv, 'password')
device = o11.parse_params(sys.argv, 'device')
pin = o11.parse_params(sys.argv, 'pin')

id = o11.parse_params(sys.argv, 'id')
action = o11.parse_params(sys.argv, 'action')

bind = o11.parse_params(sys.argv, 'bind')
proxy = o11.parse_params(sys.argv, 'proxy')
doh = o11.parse_params(sys.argv, 'doh')
worker = o11.parse_params(sys.argv, 'worker')

cdm = o11.parse_params(sys.argv, 'cdm')
drm = o11.parse_params(sys.argv, 'drm')
kid = o11.parse_params(sys.argv, 'kid')
pssh = o11.parse_params(sys.argv, 'pssh')
challenge = o11.parse_params(sys.argv, 'challenge')

heartbeaturl = o11.parse_params(sys.argv, 'heartbeaturl')
heartbeatparams = o11.parse_params(sys.argv, 'heartbeatparams')

# Session setup
o11Session = o11.session(bind=bind, proxy=proxy, worker=worker)
req = o11Session.get_session()
if doh != "":
    o11.dns(doh)

if challenge == "cert":
    challenge = "CAQ="

# Configuration
WVD_PATH = './WVD.wvd'
authFile = '/Max_token.txt'
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))

USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'

headers = {
    'accept': 'application/json, text/plain, */*',
    'origin': 'https://play.max.com',
    'referer': 'https://play.max.com/',
    'user-agent': USER_AGENT,
    'x-disco-client': 'WEB:NT 10.0:beam:4.3.0',
    'x-disco-params': 'realm=bolt,bid=beam,features=ar',
}

token = ''

def get_auth():
    try:
        with open(SCRIPT_DIR + authFile, 'r') as f:
            return f.read().strip()
    except:
        return None

def save_auth(tok):
    with open(SCRIPT_DIR + authFile, 'w') as f:
        f.write(tok)

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    tok = get_auth()
    if not tok:
        print("No token found. Please add Max 'st' cookie value to auth file.", file=sys.stderr)
        print("Copy from DevTools -> Application -> Cookies -> https://play.max.com/", file=sys.stderr)
        save_auth('')
        sys.exit(1)
    
    token = tok
    print("logged in successfully", file=sys.stderr)
    return tok

def get_token():
    global token
    if token:
        return token
    return login()

def get_pssh_from_mpd(url):
    response = req.get(url, headers={'User-Agent': USER_AGENT})
    content_protections = BeautifulSoup(response.content, features="xml").findAll('ContentProtection')
    pssh_list = []
    for cp in content_protections:
        if cp.get('schemeIdUri', '').lower() == 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed':
            p = cp.find('cenc:pssh')
            if p and p.text not in pssh_list:
                pssh_list.append(p.text)
    return pssh_list

def get_single(edit_id):
    cookies = {'st': token}
    single_headers = {**headers, 'content-type': 'application/json', 'x-wbd-preferred-language': 'en-GB,en'}
    json_data = {
        'appBundle': 'beam',
        'consumptionType': 'streaming',
        'deviceInfo': {'deviceId': 'ea6d18a7-37c4-43b5-a449-7d747b3a042c', 'browser': {'name': 'Chrome', 'version': '126.0.0.0'}, 'make': 'desktop', 'model': 'desktop', 'os': {'name': 'Windows', 'version': 'NT 10.0'}, 'platform': 'WEB', 'deviceType': 'web', 'player': {'sdk': {'name': 'Beam Player Desktop', 'version': '4.3.0'}, 'mediaEngine': {'name': 'GLUON_BROWSER', 'version': '2.15.3'}, 'playerView': {'height': 1440, 'width': 2560}}},
        'editId': edit_id,
        'capabilities': {'manifests': {'formats': {'dash': {}}}, 'codecs': {'audio': {'decoders': [{'codec': 'aac', 'profiles': ['lc', 'hev', 'hev2']}]}, 'video': {'decoders': [{'codec': 'h264', 'profiles': ['high', 'main', 'baseline'], 'maxLevel': '5.2', 'levelConstraints': {'width': {'min': 0, 'max': 755}, 'height': {'min': 0, 'max': 1279}, 'framerate': {'min': 0, 'max': 60}}}], 'hdrFormats': []}}, 'contentProtection': {'contentDecryptionModules': [{'drmKeySystem': 'clearkey'}, {'drmKeySystem': 'widevine', 'maxSecurityLevel': 'l3'}]}, 'devicePlatform': {'memory': {'allocatedMemory': 0, 'freeAvailableMemory': 1.7976931348623157e+308}, 'network': {'capabilities': {'protocols': {'http': {'byteRangeRequests': True}}}, 'lastKnownStatus': {'networkTransportType': 'unknown'}}, 'videoSink': {'capabilities': {'colorGamuts': ['standard'], 'hdrFormats': []}, 'lastKnownStatus': {'height': 1440, 'width': 2560}}}},
        'gdpr': False,
        'firstPlay': False,
        'playbackSessionId': 'ee6b97ef-cc80-458c-9d1f-6ad0d5c4037a',
        'applicationSessionId': '56ded3e9-b2e0-49fc-a6e6-49fc189faf93',
        'userPreferences': {'videoQuality': 'best', 'uiLanguage': 'en-GB'},
        'features': ['mlp'],
    }
    response = req.post('https://default.any-any.prd.api.max.com/any/playback/v1/playbackInfo', cookies=cookies, headers=single_headers, json=json_data)
    try:
        data = response.json()
        return data['manifest']['url'], data['drm']['schemes']['widevine']['licenseUrl']
    except:
        return None, None

def do_cdm_internal(challenge_b64, lic_url):
    lic_headers = {'accept': '*/*', 'origin': 'https://play.max.com', 'referer': 'https://play.max.com/', 'user-agent': USER_AGENT, 'content-type': 'application/octet-stream'}
    response = req.post(lic_url, headers=lic_headers, data=base64.b64decode(challenge_b64))
    response_b64 = str(base64.b64encode(response.content), 'ascii')
    if response_b64.startswith('CA'):
        return response_b64
    return None

def do_cdm_external(pssh_b64, lic_url):
    try:
        pssh_obj = PSSH(pssh_b64)
        device_obj = Device.load(WVD_PATH)
        cdm_obj = Cdm.from_device(device_obj)
        session_id = cdm_obj.open()
        challenge_data = cdm_obj.get_license_challenge(session_id, pssh_obj)
        lic_headers = {'accept': '*/*', 'origin': 'https://play.max.com', 'referer': 'https://play.max.com/', 'user-agent': USER_AGENT, 'content-type': 'application/octet-stream'}
        licence = req.post(lic_url, headers=lic_headers, data=challenge_data)
        cdm_obj.parse_license(session_id, licence.content)
        keys = [f"{key.kid.hex}:{key.key.hex()}" for key in cdm_obj.get_keys(session_id) if key.type != 'SIGNING']
        cdm_obj.close(session_id)
        return keys
    except Exception as e:
        print(f'CDM external failed: {e}', file=sys.stderr)
        return None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        cookies = {'st': token}
        
        included = []
        for url in ['https://default.any-amer.prd.api.max.com/cms/routes/sports?include=default&decorators=viewingHistory,isFavorite,contentAction,badges&page[items.size]=100',
                    'https://default.any-latam.prd.api.max.com/cms/routes/tnt-sports?include=default&decorators=viewingHistory,isFavorite,contentAction,badges&page[items.size]=100',
                    'https://default.any-emea.prd.api.hbomax.com/cms/routes/sports?include=default&decorators=viewingHistory,isFavorite,contentAction,badges&page[items.size]=100']:
            try:
                response = req.get(url, cookies=cookies, headers=headers)
                data = response.json()
                included += data.get('included', [])
            except:
                pass
        
        included = list({v['id']:v for v in included}.values())
        current_time = datetime.datetime.utcnow()
        
        for i in included:
            if 'attributes' in i and 'videoType' in i['attributes'] and i['attributes']['videoType'] in ['LIVE', 'LIVE_LINEAR']:
                if 'scheduleStart' in i['attributes'] and 'scheduleEnd' in i['attributes']:
                    try:
                        start_time = datetime.datetime.strptime(i['attributes']['scheduleStart'], '%Y-%m-%dT%H:%M:%SZ')
                        end_time = datetime.datetime.strptime(i['attributes']['scheduleEnd'], '%Y-%m-%dT%H:%M:%SZ')
                        if start_time <= current_time <= end_time:
                            edit_id = i.get('relationships', {}).get('edit', {}).get('data', {}).get('id', '')
                            channel = {
                                'Name': i['attributes'].get('name', 'Unknown'),
                                'Mode': 'live',
                                'SessionManifest': True,
                                'ManifestScript': f"id={edit_id}",
                                'CdmType': 'widevine',
                                'UseCdm': True,
                                'Cdm': f"id={edit_id}",
                                'Video': 'best',
                                'OnDemand': True,
                                'SpeedUp': True,
                            }
                            output['Channels'].append(channel)
                    except:
                        pass
        print(json.dumps(output, indent=2))
    
    elif action == "events":
        output = {'Events': []}
        print(json.dumps(output, indent=2))
    
    elif action == "heartbeat":
        sys.exit()
    
    elif action == "manifest":
        try:
            edit_id = id
            video_url, lic_url = get_single(edit_id)
            if not video_url:
                return "error"
            output = {
                "Cdn": [{"Name": "default", "ManifestUrl": video_url}],
                "ManifestUrl": video_url,
                "Headers": {"Manifest": {'User-Agent': USER_AGENT}, "Media": {'User-Agent': USER_AGENT}},
                "Heartbeat": {"Url": '', "Params": '', "PeriodMs": 5*60*1000},
                "LicenseUrl": lic_url
            }
            print(json.dumps(output))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "internal":
        try:
            edit_id = id
            _, lic_url = get_single(edit_id)
            if lic_url:
                result = do_cdm_internal(challenge, lic_url)
                if result:
                    print(result)
                else:
                    return "error"
            else:
                return "error"
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "external":
        try:
            edit_id = id
            video_url, lic_url = get_single(edit_id)
            if lic_url:
                pssh_list = get_pssh_from_mpd(video_url) if not pssh else [pssh]
                all_keys = []
                for p in pssh_list:
                    keys = do_cdm_external(p, lic_url)
                    if keys:
                        for k in keys:
                            if k not in all_keys:
                                all_keys.append(k)
                if all_keys:
                    for key in all_keys:
                        print(key)
                else:
                    return "error"
            else:
                return "error"
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    else:
        print("invalid action: " + action, file=sys.stderr)

if do_action() == "error":
    login()
    do_action()
