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

# 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 = '/MagentaTVPL_auth.json'
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/140.0.0.0 Safari/537.36'

token = ''
channel_map_id = ''
account_url = ''
natco_key = ''
app_key = ''
app_version = ''

def get_auth():
    try:
        return json.load(open(SCRIPT_DIR + authFile))
    except:
        return None

def save_auth(auth_data):
    json.dump(auth_data, open(SCRIPT_DIR + authFile, 'w'), indent=2)

def get_init_values():
    response = req.get('https://magentatv.pl/', headers={'Accept': 'text/html', 'User-Agent': USER_AGENT})
    for line in response.content.decode().splitlines():
        if 'window.APP_CONSTANTS' in line:
            data = json.loads(line.strip().strip('window.APP_CONSTANTS').strip().strip('=').strip())
            return data['NATCO_KEY'], data['CMS_CONFIGURATION_API_KEY'], data['APP_VERSION'], data['DEVICE_ID']
    return 'pl', '', '1.0.0', str(uuid.uuid4())

def do_refresh(refresh_token):
    global natco_key, app_key, app_version
    decoded = jwt.decode(refresh_token, options={'verify_signature': False})
    headers = {'accept': 'application/json, text/plain, */*', 'app_key': app_key, 'app_version': app_version, 'channel': 'Tv', 'content-type': 'application/json', 'device-id': decoded['dc_deviceId'], 'device-name': 'Windows - Chrome', 'origin': 'https://magentatv.pl', 'refresh_token': refresh_token, 'tenant': 'tv', 'user-agent': USER_AGENT, 'x-call-type': 'AUTH_USER'}
    json_data = {'clientVersion': app_version, 'deviceId': decoded['dc_deviceId'], 'concurrencyLimitParam': 'TVSOA-restriction-unmanagedDeviceStreamLimit'}
    response = req.post('https://gateway-pl-proxy.tv.yo-digital.com/pl-idm/P/onboarding/refresh-token', headers=headers, json=json_data)
    data = response.json()
    return data['accessToken'], data['refreshToken']

def get_account_info(tok):
    decoded = jwt.decode(tok, options={'verify_signature': False})
    headers = {'accept': 'application/json, text/plain, */*', 'app_key': app_key, 'app_version': app_version, 'bff_token': tok, 'device-id': decoded['dc_deviceId'], 'device-name': 'Windows - Chrome', 'origin': 'https://magentatv.pl', 'tenant': 'tv', 'user-agent': USER_AGENT, 'x-call-type': 'AUTH_USER'}
    params = {'fresh_login': 'false', 'app_language': 'pl', 'natco_code': 'pl'}
    response = req.get('https://tv-pl-prod.yo-digital.com/pl-bifrost/user/account', params=params, headers=headers)
    data = response.json()
    return data['channelMap_id'], data['account_url']

def login():
    global token, channel_map_id, account_url, natco_key, app_key, app_version
    print("logging in...", file=sys.stderr)
    
    natco_key, app_key, app_version, _ = get_init_values()
    
    auth = get_auth()
    if not auth or 'refresh_token' not in auth:
        print("No auth found. Please add MagentaTVPL refresh_token to auth file.", file=sys.stderr)
        save_auth({'refresh_token': ''})
        sys.exit(1)
    
    try:
        tok, new_refresh = do_refresh(auth['refresh_token'])
        save_auth({'refresh_token': new_refresh})
        token = tok
        channel_map_id, account_url = get_account_info(tok)
        print("logged in successfully", file=sys.stderr)
        return tok
    except Exception as e:
        print(f"Login failed: {e}", file=sys.stderr)
        sys.exit(1)

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')
    for cp in content_protections:
        if cp.get('schemeIdUri', '').lower() == 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed':
            pssh_elem = cp.find('cenc:pssh')
            if pssh_elem:
                return pssh_elem.text
    return None

def get_single(media_id):
    decoded = jwt.decode(token, options={'verify_signature': False})
    headers = {'accept': 'application/json, text/plain, */*', 'app_key': app_key, 'app_version': app_version, 'bff_token': token, 'device-id': decoded['dc_deviceId'], 'device-name': 'Windows - Chrome', 'origin': 'https://magentatv.pl', 'tenant': 'tv', 'user-agent': USER_AGENT, 'x-call-type': 'AUTH_USER', 'x-channel-map-id': channel_map_id}
    params = {'client_id': decoded['dc_deviceId'], 'media_id': media_id, 'natco_key': natco_key, 'src_format': 'MPEG-DASH', 'content_type': 'live', 'app_language': 'pl', 'natco_code': 'pl'}
    response = req.get('https://tv-pl-prod.yo-digital.com/pl-bifrost/media', params=params, headers=headers)
    try:
        data = response.json()
        return data['video']['video_src'], data['video']['pid'], data['lock']['lock'], data['lock']['lock_id'], data['lock']['lock_sequence_token'], data['lock']['concurrency_service_url']
    except:
        return None, None, None, None, None, None

def unlock_concurrency(lock, lock_id, lock_token, concurrency_url):
    decoded = jwt.decode(token, options={'verify_signature': False})
    params = {'_clientId': decoded['dc_deviceId'], 'form': 'json', 'schema': '1.0', 'natco_key': natco_key, '_encryptedLock': lock, '_id': lock_id, '_sequenceToken': lock_token}
    req.get(f'{concurrency_url}/web/Concurrency/unlock', params=params, headers={'accept': 'application/json, text/plain, */*', 'origin': 'https://magentatv.pl', 'user-agent': USER_AGENT})

def do_cdm_internal(challenge_b64, release_pid):
    decoded = jwt.decode(token, options={'verify_signature': False})
    lic_headers = {'accept': '*/*', 'authorization': 'Basic ' + base64.b64encode(f'{account_url}:{decoded["dc_cts_personaToken"]}'.encode('utf-8')).decode('utf-8'), 'content-type': 'application/octet-stream', 'origin': 'https://magentatv.pl', 'user-agent': USER_AGENT}
    params = {'schema': '1.0', 'form': 'json', 'releasePid': release_pid}
    response = req.post('https://widevine.entitlement.theplatform.eu/wv/web/ModularDrm/getRawWidevineLicense', headers=lic_headers, params=params, 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, release_pid):
    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)
        decoded = jwt.decode(token, options={'verify_signature': False})
        lic_headers = {'accept': '*/*', 'authorization': 'Basic ' + base64.b64encode(f'{account_url}:{decoded["dc_cts_personaToken"]}'.encode('utf-8')).decode('utf-8'), 'content-type': 'application/octet-stream', 'origin': 'https://magentatv.pl', 'user-agent': USER_AGENT}
        params = {'schema': '1.0', 'form': 'json', 'releasePid': release_pid}
        licence = req.post('https://widevine.entitlement.theplatform.eu/wv/web/ModularDrm/getRawWidevineLicense', headers=lic_headers, params=params, 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': []}
        decoded = jwt.decode(token, options={'verify_signature': False})
        headers = {'accept': 'application/json, text/plain, */*', 'app_key': app_key, 'app_version': app_version, 'bff_token': token, 'device-id': decoded['dc_deviceId'], 'device-name': 'Windows - Chrome', 'origin': 'https://magentatv.pl', 'tenant': 'tv', 'user-agent': USER_AGENT, 'x-call-type': 'AUTH_USER', 'x-channel-map-id': channel_map_id}
        params = {'natco_key': natco_key, 'channelMap_id': channel_map_id, 'includeVirtualChannels': 'true', 'includeSyntheticChannels': 'false', 'app_language': 'pl', 'natco_code': 'pl'}
        response = req.get('https://tv-pl-prod.yo-digital.com/pl-bifrost/epg/channel', params=params, headers=headers)
        try:
            data = response.json()
            for ch in data.get('channels', []):
                media_id = ch.get('media_pid', '')
                channel = {
                    'Name': ch.get('title', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={media_id}",
                    'CdmType': 'widevine',
                    'UseCdm': True,
                    'Cdm': f"id={media_id}",
                    'Video': 'best',
                    'OnDemand': True,
                    'SpeedUp': True,
                }
                output['Channels'].append(channel)
            print(json.dumps(output, indent=2))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "events":
        output = {'Events': []}
        print(json.dumps(output, indent=2))
    
    elif action == "heartbeat":
        sys.exit()
    
    elif action == "manifest":
        try:
            media_id = id
            video_url, release_pid, lock, lock_id, lock_token, concurrency_url = get_single(media_id)
            if video_url and lock:
                unlock_concurrency(lock, lock_id, lock_token, concurrency_url)
            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},
                "ReleasePid": release_pid
            }
            print(json.dumps(output))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "internal":
        try:
            media_id = id
            video_url, release_pid, lock, lock_id, lock_token, concurrency_url = get_single(media_id)
            if video_url and lock:
                unlock_concurrency(lock, lock_id, lock_token, concurrency_url)
            if release_pid:
                result = do_cdm_internal(challenge, release_pid)
                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:
            media_id = id
            video_url, release_pid, lock, lock_id, lock_token, concurrency_url = get_single(media_id)
            if video_url and lock:
                unlock_concurrency(lock, lock_id, lock_token, concurrency_url)
            if release_pid:
                pssh_to_use = pssh if pssh else get_pssh_from_mpd(video_url)
                if pssh_to_use:
                    keys = do_cdm_external(pssh_to_use, release_pid)
                    if keys:
                        for key in keys:
                            print(key)
                    else:
                        return "error"
                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()
