#!/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

# 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 = '/PlayPlus_token.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,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'Referer': 'https://www.playplus.com/live',
    'User-Agent': USER_AGENT,
}

x_playplus = ''

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 check_token(tok):
    cookies = {'_X_PLAYPLUS': tok}
    response = req.get('https://www.playplus.com/account/acesso', cookies=cookies, headers=headers, allow_redirects=False)
    response.raise_for_status()
    if 'Location' in response.headers:
        raise Exception('Invalid token')

def login():
    global x_playplus
    print("logging in...", file=sys.stderr)
    
    tok = get_auth()
    if not tok:
        print("No token found. Please add PlayPlus _X_PLAYPLUS cookie to auth file.", file=sys.stderr)
        print("Login to https://www.playplus.com/ and copy _X_PLAYPLUS cookie value", file=sys.stderr)
        save_auth('')
        sys.exit(1)
    
    try:
        check_token(tok)
        x_playplus = 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 x_playplus
    if x_playplus:
        return x_playplus
    return login()

def get_single(url):
    cookies = {'_X_PLAYPLUS': x_playplus}
    response = req.get(url, cookies=cookies, headers=headers)
    try:
        data = response.content.decode()
        stream_url = data.split("var urlLive = '")[-1].split("'")[0]
        if len(stream_url) == 0 or not stream_url.startswith('http'):
            return None
        return stream_url
    except:
        return None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        cookies = {'_X_PLAYPLUS': x_playplus}
        response = req.get('https://www.playplus.com/live', cookies=cookies, headers=headers)
        try:
            soup = BeautifulSoup(response.content, features='lxml')
            channel_items = soup.find_all('div', {'class': 'channel-item'})
            for ci in channel_items:
                title = ci.find('p').text if ci.find('p') else 'Unknown'
                href = 'https://www.playplus.com/' + ci.find('a')['href'] if ci.find('a') else ''
                channel = {
                    'Name': title,
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"url={href}",
                    'CdmType': 'none',
                    'UseCdm': False,
                    'Cdm': '',
                    '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:
            page_url = id.replace('url=', '')
            video_url = get_single(page_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}
            }
            print(json.dumps(output))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm":
        print("PlayPlus streams are typically unencrypted HLS", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

if do_action() == "error":
    login()
    do_action()
