#!/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 = '/MegoGo_urt3.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': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'User-Agent': USER_AGENT,
}

urt3 = ''
csrf_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 urt3, csrf_token
    print("logging in...", file=sys.stderr)
    
    tok = get_auth()
    if not tok:
        print("No urt3 found. Please add MegoGo urt3 cookie to auth file.", file=sys.stderr)
        print("Login to https://megogo.net and copy 'urt3' cookie value", file=sys.stderr)
        save_auth('')
        sys.exit(1)
    
    urt3 = tok
    req.cookies.set('urt3', urt3)
    
    # Get CSRF token
    response = req.get('https://megogo.net/en/tv', headers=headers)
    soup = BeautifulSoup(response.content, features='lxml')
    csrf_token = soup.find('html').get('data-csrf-token', '')
    
    print("logged in successfully", file=sys.stderr)
    return tok

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

def find_wv_pssh_offsets(raw):
    offsets = []
    offset = 0
    while True:
        offset = raw.find(b'pssh', offset)
        if offset == -1:
            break
        size = int.from_bytes(raw[offset-4:offset], byteorder='big')
        pssh_offset = offset - 4
        offsets.append(raw[pssh_offset:pssh_offset+size])
        offset += size
    return offsets

def to_pssh(content):
    wv_offsets = find_wv_pssh_offsets(content)
    return [base64.b64encode(wv_offset).decode() for wv_offset in wv_offsets]

def get_pssh_from_mpd(url):
    response = req.get(url, headers={'User-Agent': USER_AGENT, 'Origin': 'https://megogo.net', 'Referer': 'https://megogo.net/'})
    try:
        soup = BeautifulSoup(response.content, features="xml")
        content_protections = soup.findAll('ContentProtection')
        for cp in content_protections:
            if cp.get('schemeIdUri', '') == 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed':
                pssh_elem = cp.find('cenc:pssh')
                if pssh_elem:
                    return str(response.url), pssh_elem.text
        
        # Try init segment
        representation = soup.find_all('Representation')[-1]
        initialization = soup.find('SegmentTemplate')['initialization']
        rep_id = representation['id']
        bandwidth = representation['bandwidth']
        loc_parts = str(response.url).split('/')
        loc_parts.pop()
        init_url = '/'.join(loc_parts) + '/' + initialization.replace('$RepresentationID$', rep_id).replace('$Bandwidth$', bandwidth)
        init_response = req.get(init_url, headers={'User-Agent': USER_AGENT})
        psshs = to_pssh(init_response.content)
        return str(response.url), min(psshs, key=len) if psshs else None
    except:
        return str(response.url), None

def get_single(channel_id):
    single_headers = {
        'Accept': '*/*',
        'Csrf-Token': csrf_token,
        'Referer': 'https://megogo.net/en/tv/channels/',
        'User-Agent': USER_AGENT,
        'X-Requested-With': 'XMLHttpRequest',
    }
    params = {'lang': 'en', 'obj_id': channel_id, 'drm_type': 'modular'}
    response = req.get('https://megogo.net/wb/desktop-megogo-tvVideoEmbed_v1/stream', params=params, headers=single_headers)
    try:
        data = response.json()
        tv_embed = data['data']['widgets']['desktop-megogo-tvVideoEmbed_v1']['json']
        return tv_embed['src'], tv_embed.get('license_server')
    except:
        return None, None

def do_cdm_internal(challenge_b64, lic_url):
    lic_headers = {
        'Origin': 'https://megogo.net',
        'Referer': 'https://megogo.net/',
        '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 = {
            'Origin': 'https://megogo.net',
            'Referer': 'https://megogo.net/',
            '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 = []
        for key in cdm_obj.get_keys(session_id):
            if key.type != 'SIGNING':
                keys.append(f"{key.kid.hex}:{key.key.hex()}")
        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': []}
        response = req.get('https://megogo.net/en/tv', headers=headers)
        try:
            soup = BeautifulSoup(response.content, features='lxml')
            sections = soup.find_all('section')
            channels = []
            for s in sections:
                data_init_app = s.get('data-init-app')
                if data_init_app:
                    data = json.loads(data_init_app.replace('&quot;', '"'))
                    for g in data.get('tvChannelsGrouped', {}).get('channel_groups', []):
                        channels += g.get('objects', [])
            
            unique = {item['id']: item for item in channels}
            for ch in unique.values():
                channel = {
                    'Name': ch.get('title', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={ch.get('id', '')}",
                    'CdmType': 'widevine',
                    'UseCdm': True,
                    'Cdm': f"id={ch.get('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:
            channel_id = id
            video_url, lic_url = get_single(channel_id)
            if not video_url:
                return "error"
            
            final_url, _ = get_pssh_from_mpd(video_url)
            
            output = {
                "Cdn": [{"Name": "default", "ManifestUrl": final_url}],
                "ManifestUrl": final_url,
                "Headers": {"Manifest": {'User-Agent': USER_AGENT, 'Origin': 'https://megogo.net', 'Referer': 'https://megogo.net/'}, "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:
            channel_id = id
            _, lic_url = get_single(channel_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:
            channel_id = id
            video_url, lic_url = get_single(channel_id)
            if lic_url:
                _, pssh_to_use = get_pssh_from_mpd(video_url) if not pssh else (None, pssh)
                if pssh_to_use:
                    keys = do_cdm_external(pssh_to_use, lic_url)
                    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()
