#!/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 = '/tv2_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'

headers = {
    'accept': '*/*',
    'origin': 'https://play.tv2.no',
    'referer': 'https://play.tv2.no/',
    'user-agent': USER_AGENT,
}

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 do_refresh(client_id, refresh_token):
    refresh_headers = {
        'accept': '*/*',
        'auth0-client': 'eyJuYW1lIjoiYXV0aDAtcmVhY3QiLCJ2ZXJzaW9uIjoiMS4xMC4xIn0=',
        'content-type': 'application/json',
        'origin': 'https://play.tv2.no',
        'referer': 'https://play.tv2.no/',
        'user-agent': USER_AGENT,
    }
    json_data = {'grant_type': 'refresh_token', 'client_id': client_id, 'refresh_token': refresh_token}
    response = req.post('https://id.tv2.no/oauth/token', headers=refresh_headers, json=json_data)
    response.raise_for_status()
    data = response.json()
    return data['access_token'], data['refresh_token']

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'body' not in auth:
        print("No auth found. Please add tv2 auth to auth file.", file=sys.stderr)
        print("Login to https://play.tv2.no and copy '@@auth0spajs@@' from Local Storage", file=sys.stderr)
        save_auth({'body': {'client_id': 'ENTER_CLIENT_ID_HERE', 'refresh_token': 'ENTER_REFRESH_TOKEN_HERE'}})
        sys.exit(1)
    
    try:
        client_id = auth['body']['client_id']
        refresh_token = auth['body']['refresh_token']
        tok, new_refresh = do_refresh(client_id, refresh_token)
        auth['body']['refresh_token'] = new_refresh
        save_auth(auth)
        token = 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})
    try:
        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 str(response.url), pssh_elem.text
    except:
        pass
    return str(response.url), None

def get_single(content_id):
    single_headers = {
        'accept': 'application/json;v=3',
        'authorization': 'Bearer ' + token,
        'content-type': 'application/json',
        'origin': 'https://play.tv2.no',
        'referer': 'https://play.tv2.no/',
        'user-agent': USER_AGENT,
    }
    json_data = {'device': {'id': '1-1-1', 'name': 'Nettleser (HTML)'}, 'adsDeviceId': 'b17904af-6bc1-4047-8fb5-e00b96aa1c12'}
    response = req.post(f'https://api.play.tv2.no/play/{content_id}', params={'stream': 'DASH'}, headers=single_headers, json=json_data)
    try:
        data = response.json()
        stream = data['playback']['streams'][0]
        lic_url = None
        lic_headers = {}
        if 'license' in stream and stream['license']:
            lic_url = stream['license']['url']
            for h in stream['license'].get('headers', []):
                lic_headers[h['name']] = h['value']
        return stream['url'], lic_url, lic_headers
    except:
        return None, None, None

def do_cdm_internal(challenge_b64, lic_url, lic_headers):
    req_headers = {
        'accept': '*/*',
        'origin': 'https://play.tv2.no',
        'referer': 'https://play.tv2.no/',
        'user-agent': USER_AGENT,
        'content-type': 'application/octet-stream',
    }
    req_headers.update(lic_headers)
    response = req.post(lic_url, headers=req_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_headers):
    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)
        req_headers = {
            'accept': '*/*',
            'origin': 'https://play.tv2.no',
            'referer': 'https://play.tv2.no/',
            'user-agent': USER_AGENT,
            'content-type': 'application/octet-stream',
        }
        req_headers.update(lic_headers)
        licence = req.post(lic_url, headers=req_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': []}
        ch_headers = {**headers, 'authorization': 'Bearer ' + token}
        response = req.get('https://ai.play.tv2.no/v1/epg/all', headers=ch_headers)
        try:
            data = response.json()
            for ch in data.get('channels', []):
                channel = {
                    'Name': ch.get('title', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={ch.get('content_id', '')}",
                    'CdmType': 'widevine',
                    'UseCdm': True,
                    'Cdm': f"id={ch.get('content_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:
            content_id = id
            video_url, lic_url, lic_headers = get_single(content_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}, "Media": {'User-Agent': USER_AGENT}},
                "Heartbeat": {"Url": '', "Params": '', "PeriodMs": 5*60*1000},
                "LicenseUrl": lic_url,
                "LicenseHeaders": lic_headers
            }
            print(json.dumps(output))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "internal":
        try:
            content_id = id
            _, lic_url, lic_headers = get_single(content_id)
            if lic_url:
                result = do_cdm_internal(challenge, lic_url, lic_headers)
                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:
            content_id = id
            video_url, lic_url, lic_headers = get_single(content_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, lic_headers)
                    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()
