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

country = o11.parse_params(sys.argv, 'country')

# 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 = '/Clubber_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/140.0.0.0 Safari/537.36'

# Set domains based on country
if country.lower() == 'gb':
    LOGIN_DOMAIN = 'ukusersservice-b9fjgrhje9ebgmba.westeurope-01.azurewebsites.net'
    API_DOMAIN = 'ukgameservice-evdqecczd6guhtft.westeurope-01.azurewebsites.net'
else:  # Default to IE
    LOGIN_DOMAIN = 'clubberusersprod.azurewebsites.net'
    API_DOMAIN = 'prodgameservicecontainer.azurewebsites.net'

headers = {
    'accept': 'application/json, text/plain, */*',
    'origin': 'https://clubber.ie',
    'referer': 'https://clubber.ie/',
    '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 check_token(tok):
    check_headers = {**headers, 'authorization': 'Bearer ' + tok}
    response = req.get(f'https://{API_DOMAIN}/api/Game/GetGAAGamesByGameState', params={'gameState': '1'}, headers=check_headers)
    response.raise_for_status()

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if auth and 'token' in auth:
        try:
            check_token(auth['token'])
            token = auth['token']
            print("logged in successfully (cached token)", file=sys.stderr)
            return token
        except:
            pass
    
    print("No valid token found. Please add Clubber auth to auth file.", file=sys.stderr)
    save_auth({'token': 'ENTER_TOKEN_HERE'})
    sys.exit(1)

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

def get_single(event_id):
    single_headers = {**headers, 'authorization': 'Bearer ' + token}
    params = {'id': event_id, 'os': 'desktop Windows version windows-10 Chrome version 140.0.0.0 oriantation portrait'}
    response = req.get(f'https://{API_DOMAIN}/api/Game/getGameWithAds', params=params, headers=single_headers)
    try:
        return response.json()['result']['videoLink']
    except:
        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(f'https://{API_DOMAIN}/api/Game/GetGAAGamesByGameState', params={'gameState': '1'}, headers=ch_headers)
        try:
            data = response.json()
            for e in data.get('result', []):
                if 'teams' in e:
                    title = f"{e['teams']['clubName']} v {e['teams']['competitorClubName']}"
                    channel = {
                        'Name': title,
                        'Mode': 'live',
                        'SessionManifest': True,
                        'ManifestScript': f"id={e.get('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:
            event_id = id
            video_url = get_single(event_id)
            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("Clubber streams are typically unencrypted HLS", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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