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

# Configuration
WVD_PATH = './WVD.wvd'
authFile = '/RACINGTV_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'
OUTLET_AUTH_KEY = '18arele3k5ry51xfcefkic6f5o'
API_KEY = '82efe8af-c962-414a-8110-96ddd277d346'

headers = {
    'accept': 'application/json',
    'content-type': 'application/json',
    'origin': 'https://www.racingtv.com',
    'referer': 'https://www.racingtv.com/',
    'user-agent': USER_AGENT,
    'x-requested-with': 'racingtv-web/5.3.0',
}

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 check_token(tok):
    response = req.get('https://api.racingtv.com/member/accounts', headers={**headers, 'authorization': 'Bearer ' + tok})
    response.raise_for_status()

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    tok = get_auth()
    if not tok:
        print("No token found. Please add RacingTV JWT token to auth file.", file=sys.stderr)
        save_auth('')
        sys.exit(1)
    
    try:
        check_token(tok)
        token = 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 token
    if token:
        return token
    return login()

def get_single(source_event_type, channel_id):
    response = req.get(f'https://api.racingtv.com/member/watch/streams/{source_event_type}/{channel_id}', headers={**headers, 'authorization': 'Bearer ' + token})
    try:
        data = response.json()
        return data['player']['sources'][0]['url']
    except:
        return None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        response = req.get('https://api.racingtv.com/videos/streams', headers=headers)
        try:
            data = response.json()
            for ch in data.get('streams', []):
                source_event_type = ch.get('source_event_type', 'channel')
                if source_event_type != 'channel':
                    source_event_type += 's'
                channel = {
                    'Name': ch.get('title', 'Unknown').replace('/', '-'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={ch.get('id', '')}&type={source_event_type}",
                    '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
            channel_id = params_dict.get('id', '')
            source_event_type = params_dict.get('type', 'channel')
            
            video_url = get_single(source_event_type, channel_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("RacingTV uses unencrypted HLS streams", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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