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

# 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 = '/GaaPlus_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 = {
    'User-Agent': USER_AGENT,
    'Accept': '*/*',
    'Origin': 'https://www.gaaplus.ie',
    'Referer': 'https://www.gaaplus.ie/',
}

remember_token = ''

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 login():
    global remember_token
    print("logging in...", file=sys.stderr)
    
    tok = get_auth()
    if not tok:
        print("No token found. Please add GaaPlus remember_token to auth file.", file=sys.stderr)
        print("Login to https://www.gaaplus.ie/ and copy remember_token cookie", file=sys.stderr)
        save_auth('')
        sys.exit(1)
    
    remember_token = tok
    print("logged in successfully", file=sys.stderr)
    return tok

def get_token():
    global remember_token
    if remember_token:
        return remember_token
    return login()

def get_key(rte_product_id):
    cookies = {'remember_token': remember_token, 'remember_me': 'true'}
    key_headers = {**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.gaaplus.ie/matches/live'}
    response = req.get(f'https://www.gaaplus.ie/fixture/{rte_product_id}', headers=key_headers, cookies=cookies)
    try:
        key = response.content.decode().split('data-key="')[-1].split('"')[0]
        if len(key) == 30:
            return key
    except:
        pass
    return None

def get_single(key, msp_id):
    single_headers = {**headers, 'Uvid': msp_id}
    params = {'key': key, 'platform': 'chrome'}
    response = req.get(f'https://v2-streams-elb.simplestreamcdn.com/api/event/stream/{msp_id}', headers=single_headers, params=params)
    try:
        return response.json()['response']['stream']
    except:
        return None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        ch_headers = {**headers, 'X-Requested-With': 'XMLHttpRequest', 'Referer': 'https://www.gaaplus.ie/matches/live'}
        response = req.get('https://www.gaaplus.ie/core/api/getLiveMatches', headers=ch_headers)
        try:
            data = response.json()
            for fixture in data.get('data', {}).get('fixtures', []):
                msp_id = fixture.get('msp_id', '')
                rte_product_id = fixture.get('rte_product_id', '')
                channel = {
                    'Name': fixture.get('product_name', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"msp={msp_id}&rte={rte_product_id}",
                    '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:
            params_dict = {}
            for param in id.split('&'):
                if '=' in param:
                    k, v = param.split('=', 1)
                    params_dict[k] = v
            msp_id = params_dict.get('msp', '')
            rte_product_id = params_dict.get('rte', '')
            
            # Try direct URL first
            video_url = f'https://event-gaa.simplestreamcdn.com/{rte_product_id}/index.m3u8'
            
            # If direct doesn't work, get key and use API
            key = get_key(rte_product_id)
            if key:
                api_url = get_single(key, msp_id)
                if api_url:
                    video_url = api_url
            
            output = {
                "Cdn": [{"Name": "default", "ManifestUrl": video_url}],
                "ManifestUrl": video_url,
                "Headers": {"Manifest": {'User-Agent': USER_AGENT, 'Origin': 'https://www.gaaplus.ie', 'Referer': 'https://www.gaaplus.ie/'}, "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("GaaPlus streams are typically unencrypted HLS", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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