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

# Configuration
WVD_PATH = './WVD.wvd'
authFile = '/PrimaPlay_cookies.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/131.0.0.0 Safari/537.36'

cookies = {}

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_cookies(ck):
    headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9', 'Referer': 'https://www.primaplay.ro/', 'User-Agent': USER_AGENT}
    response = req.get('https://www.primaplay.ro/myaccount', headers=headers, cookies=ck)
    soup = BeautifulSoup(response.content, features='lxml')
    soup.find('h1', {'class': 'title-bg bg-account'})

def login():
    global cookies
    print("logging in...", file=sys.stderr)
    
    ck = get_auth()
    if not ck:
        print("No cookies found. Please add PrimaPlay cookies to auth file.", file=sys.stderr)
        save_auth({})
        sys.exit(1)
    
    try:
        check_cookies(ck)
        cookies = ck
        print("logged in successfully", file=sys.stderr)
        return cookies
    except Exception as e:
        print(f"Login failed: {e}", file=sys.stderr)
        sys.exit(1)

def get_cookies():
    global cookies
    if cookies:
        return cookies
    return login()

def get_single(href):
    headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9', 'user-agent': USER_AGENT}
    response = req.get(href, cookies=cookies, headers=headers)
    try:
        soup = BeautifulSoup(response.content, features='lxml')
        vid_div = soup.find('div', {'id': 'video_thumb'})
        script_tag = vid_div.find('script')
        return script_tag['src']
    except:
        return None

def extract_m3u8(script_url):
    headers = {'accept': '*/*', 'referer': 'https://www.primaplay.ro/', 'user-agent': USER_AGENT}
    response = req.get(script_url, headers=headers)
    try:
        data = response.content.decode()
        m3u8_url = data.split('vidWrap.setAttribute("data-playurl","')[-1].split('"')[0]
        return m3u8_url
    except:
        return None

def do_action():
    get_cookies()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9', 'referer': 'https://www.primaplay.ro/live/primasport1', 'user-agent': USER_AGENT}
        response = req.get('https://www.primaplay.ro/live', cookies=cookies, headers=headers)
        try:
            soup = BeautifulSoup(response.content, features='lxml')
            cards = soup.find_all('a', {'class': 'card-content'})
            for c in cards:
                channel = {
                    'Name': c.find('span').text,
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"href={c['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:
            href = id.replace('href=', '')
            script_url = get_single(href)
            if not script_url:
                return "error"
            video_url = extract_m3u8(script_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("PrimaPlay uses unencrypted HLS streams", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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