#!/usr/bin/python3
import sys
import os
import base64
import json
import datetime
import pytz
import jwt
from datetime import timezone, timedelta
from urllib.parse import unquote

# 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 = '/BeinConnectAU_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/126.0.0.0 Safari/537.36'

token = ''

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 check_token(tok):
    cookies = {'CountryCode': 'AU', 'NEXT_LOCALE': 'en'}
    headers = {'content-type': 'text/plain;charset=UTF-8', 'origin': 'https://connect-au.beinsports.com', 'referer': 'https://connect-au.beinsports.com/en/tvguide', 'user-agent': USER_AGENT}
    today = datetime.datetime.now(timezone.utc).date()
    start_time = datetime.datetime.combine(today - timedelta(days=1), datetime.datetime.min.time(), tzinfo=timezone.utc).replace(hour=22)
    end_time = datetime.datetime.combine(today, datetime.datetime.min.time(), tzinfo=timezone.utc).replace(hour=21, minute=59, second=59)
    decoded = jwt.decode(tok, options={'verify_signature': False})
    json_data = {'path': '/api/broadcast/tvguides', 'auth': decoded['accesstoken'].split('&')[0], 'body': {'StartTime': start_time.strftime('%Y-%m-%dT%H:%M:%SZ'), 'EndTime': end_time.strftime('%Y-%m-%dT%H:%M:%SZ'), 'OnlyLiveEvents': True, 'ChannelId': 'string'}}
    response = req.post('https://connect-au.beinsports.com/api/service', cookies=cookies, headers=headers, json=json_data)
    response.raise_for_status()

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'token' not in auth:
        print("No auth found. Please add BeinConnectAU token to auth file.", file=sys.stderr)
        save_auth({'token': ''})
        sys.exit(1)
    
    try:
        check_token(auth['token'])
        token = auth['token']
        print("logged in successfully", file=sys.stderr)
        return token
    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(channel_id):
    cookies = {'CountryCode': 'AU', 'host': 'connect-au.beinsports.com', 'NEXT_LOCALE': 'en', 'token': token}
    headers = {'accept': '*/*', 'next-router-state-tree': '%5B%22%22%2C%7B%22children%22%3A%5B%5B%22lang%22%2C%22en%22%2C%22d%22%5D%2C%7B%22children%22%3A%5B%22(pages)%22%2C%7B%22children%22%3A%5B%22tvguide%22%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2C%22%2Fen%2Ftvguide%22%2C%22refresh%22%5D%7D%5D%7D%5D%7D%5D%7D%2Cnull%2Cnull%2Ctrue%5D', 'next-url': '/en/tvguide', 'priority': 'u=1, i', 'referer': 'https://connect-au.beinsports.com/en/tvguide', 'rsc': '1', 'user-agent': USER_AGENT}
    params = {'_rsc': '1fx9a'}
    response = req.get(f'https://connect-au.beinsports.com/tv/{channel_id}', params=params, cookies=cookies, headers=headers)
    try:
        data = None
        for line in response.content.decode('utf-8').splitlines():
            if 'playResponse' in line:
                try:
                    data = json.loads(line.strip('5:'))
                except:
                    pass
        if not data:
            return None, None, None, None
        data = data[1][3]['playResponse']['Data']
        return data['PlayUrl'], data['DrmRightsUrl'], data['DrmToken'], data['DrmTicket']
    except:
        return None, None, None, None

def do_cdm_internal(challenge_b64, lic_url, lic_token, lic_ticket):
    lic_headers = {'Accept': '*/*', 'Authorization': lic_token, 'Origin': 'https://connect-au.beinsports.com', 'Referer': 'https://connect-au.beinsports.com/', 'User-Agent': USER_AGENT, 'X-CB-Ticket': lic_ticket, '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, lic_token, lic_ticket):
    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': '*/*', 'Authorization': lic_token, 'Origin': 'https://connect-au.beinsports.com', 'Referer': 'https://connect-au.beinsports.com/', 'User-Agent': USER_AGENT, 'X-CB-Ticket': lic_ticket, '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 = {'CountryCode': 'AU', 'NEXT_LOCALE': 'en'}
        headers = {'content-type': 'text/plain;charset=UTF-8', 'origin': 'https://connect-au.beinsports.com', 'referer': 'https://connect-au.beinsports.com/en/tvguide', 'user-agent': USER_AGENT}
        today = datetime.datetime.now(timezone.utc).date()
        start_time = datetime.datetime.combine(today - timedelta(days=1), datetime.datetime.min.time(), tzinfo=timezone.utc).replace(hour=22)
        end_time = datetime.datetime.combine(today, datetime.datetime.min.time(), tzinfo=timezone.utc).replace(hour=21, minute=59, second=59)
        decoded = jwt.decode(token, options={'verify_signature': False})
        json_data = {'path': '/api/broadcast/tvguides', 'auth': decoded['accesstoken'].split('&')[0], 'body': {'StartTime': start_time.strftime('%Y-%m-%dT%H:%M:%SZ'), 'EndTime': end_time.strftime('%Y-%m-%dT%H:%M:%SZ'), 'OnlyLiveEvents': True, 'ChannelId': 'string'}}
        response = req.post('https://connect-au.beinsports.com/api/service', cookies=cookies, headers=headers, json=json_data)
        try:
            data = response.json()
            for ch in data.get('Data', {}).get('Items', []):
                channel = {
                    'Name': ch.get('Channel', {}).get('Name', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={ch.get('Channel', {}).get('Id', '')}",
                    'CdmType': 'widevine',
                    'UseCdm': True,
                    'Cdm': f"id={ch.get('Channel', {}).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, lic_token_val, lic_ticket = get_single(channel_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,
                "LicenseToken": lic_token_val,
                "LicenseTicket": lic_ticket
            }
            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
            video_url, lic_url, lic_token_val, lic_ticket = get_single(channel_id)
            if lic_url and lic_token_val and lic_ticket:
                result = do_cdm_internal(challenge, lic_url, lic_token_val, lic_ticket)
                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, lic_token_val, lic_ticket = get_single(channel_id)
            if lic_url and lic_token_val and lic_ticket:
                pssh_to_use = pssh if pssh else get_pssh_from_mpd(video_url)
                if pssh_to_use:
                    keys = do_cdm_external(pssh_to_use, lic_url, lic_token_val, lic_ticket)
                    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()
