#!/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 = '/PilotWP_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': 'application/json, text/plain, */*',
    'referer': 'https://pilot.wp.pl/tv/',
    'user-agent': USER_AGENT,
}

sess_id = ''
sess_val = ''

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(sid, sval):
    cookies = {'netviapisessid': sid, 'netviapisessval': sval, 'loggedIn': '1', 'userType': 'premium'}
    response = req.get('https://pilot.wp.pl/api/v3/channels/favourites', params={'device_type': 'web'}, cookies=cookies, headers=headers)
    response.raise_for_status()
    new_cookies = response.cookies.get_dict()
    if 'netviapisessid' in new_cookies:
        sid = new_cookies['netviapisessid']
    if 'netviapisessval' in new_cookies:
        sval = new_cookies['netviapisessval']
    return sid, sval

def login():
    global sess_id, sess_val
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'netviapisessid' not in auth:
        print("No auth found. Please add PilotWP session cookies to auth file.", file=sys.stderr)
        print("Login to https://pilot.wp.pl/ and copy netviapisessid and netviapisessval cookies", file=sys.stderr)
        save_auth({'netviapisessid': '', 'netviapisessval': ''})
        sys.exit(1)
    
    try:
        sid, sval = do_refresh(auth['netviapisessid'], auth['netviapisessval'])
        save_auth({'netviapisessid': sid, 'netviapisessval': sval})
        sess_id = sid
        sess_val = sval
        print("logged in successfully", file=sys.stderr)
        return sid
    except Exception as e:
        print(f"Login failed: {e}", file=sys.stderr)
        sys.exit(1)

def get_token():
    global sess_id, sess_val
    if sess_id:
        return sess_id
    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, 'content-type': 'application/octet-stream'})
    location = response.url
    soup = BeautifulSoup(response.content, features="xml")
    init = soup.find('SegmentTemplate')['initialization']
    bandwidth = soup.find('Representation')['bandwidth']
    rep_id = soup.find('Representation')['id']
    base_url = soup.find('BaseURL')
    base_url_text = base_url.text if base_url else ''
    loc_parts = location.split('/')
    loc_parts.pop()
    if 'http' in base_url_text:
        init_url = base_url_text + init.replace('$Bandwidth$', bandwidth).replace('$RepresentationID$', rep_id)
    else:
        init_url = '/'.join(loc_parts) + '/' + init.replace('$Bandwidth$', bandwidth).replace('$RepresentationID$', rep_id)
    init_response = req.get(init_url, headers={'user-agent': USER_AGENT})
    psshs = to_pssh(init_response.content)
    return min(psshs, key=len) if psshs else None

def get_single(channel_id):
    cookies = {'netviapisessid': sess_id, 'netviapisessval': sess_val, 'loggedIn': '1', 'userType': 'premium'}
    response = req.get(f'https://pilot.wp.pl/api/v3/channel/{channel_id}', params={'device_type': 'web'}, cookies=cookies, headers=headers)
    try:
        data = response.json()
        stream_channel = data['data']['stream_channel']
        lic_url = None
        if 'drms' in stream_channel and stream_channel['drms'] and 'widevine' in stream_channel['drms']:
            lic_url = stream_channel['drms']['widevine']
        return stream_channel['streams'][0]['url'][0], lic_url, data['data']['token']
    except:
        return None, None, None

def close_stream(watch_token):
    cookies = {'netviapisessid': sess_id, 'netviapisessval': sess_val, 'loggedIn': '1', 'userType': 'premium'}
    close_headers = {**headers, 'content-type': 'application/json', 'origin': 'https://pilot.wp.pl'}
    req.post('https://pilot.wp.pl/api/v2/channels/close', params={'device_type': 'web'}, cookies=cookies, headers=close_headers, json={'token': watch_token})

def do_cdm_internal(challenge_b64, lic_url):
    lic_headers = {'origin': 'https://pilot.wp.pl', 'referer': 'https://pilot.wp.pl/program/tvn/', 'user-agent': USER_AGENT, 'content-type': 'application/octet-stream'}
    response = req.post('https://pilot.wp.pl' + 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://pilot.wp.pl', 'referer': 'https://pilot.wp.pl/program/tvn/', 'user-agent': USER_AGENT, 'content-type': 'application/octet-stream'}
        licence = req.post('https://pilot.wp.pl' + 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': []}
        response = req.get('https://pilot.wp.pl/api/v3/guest/channels/list', params={'device_type': 'web'}, headers=headers)
        try:
            data = response.json()
            for ch in data.get('data', []):
                channel = {
                    'Name': ch.get('name', '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, watch_token = get_single(channel_id)
            if not video_url:
                return "error"
            if 'wp_' in video_url:
                video_url = video_url.split('?')[0]
                close_stream(watch_token)
            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": 'https://pilot.wp.pl' + lic_url if lic_url else ''
            }
            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, watch_token = get_single(channel_id)
            if 'wp_' in video_url:
                close_stream(watch_token)
            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, watch_token = get_single(channel_id)
            if 'wp_' in video_url:
                video_url = video_url.split('?')[0]
                close_stream(watch_token)
            if lic_url:
                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)
                    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()
