#!/usr/bin/python3
import sys
import os
import base64
import json
import datetime
import pytz
import uuid

# 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 = '/VoyoHr_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/126.0.0.0 Safari/537.36'

token = ''
device_id = ''

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, dev_id):
    headers = {'accept': 'application/json, text/plain, */*', 'authorization': tok, 'content-type': 'application/graphql', 'device-id': dev_id, 'onl-location': 'https://voyo.rtl.hr/postavke/uredaji', 'origin': 'https://voyo.rtl.hr', 'referer': 'https://voyo.rtl.hr/postavke/uredaji', 'user-agent': USER_AGENT}
    data = '{a723710259: loginInfo ( token: "' + tok + '" siteId: 30005 ) { token nickname avatar email deviceId profileId id isSubscribed emailStatus phoneStatus } }'
    response = req.post('https://gql.voyo.hr/graphql/?raw', headers=headers, data=data)
    response.raise_for_status()
    resp_data = response.json()
    if 'errors' in resp_data and not resp_data['data']['a723710259']:
        raise Exception('Invalid token')

def login():
    global token, device_id
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'token' not in auth:
        print("No auth found. Please add VoyoHr token and device_id to auth file.", file=sys.stderr)
        save_auth({'token': '', 'device_id': str(uuid.uuid4())})
        sys.exit(1)
    
    try:
        check_token(auth['token'], auth['device_id'])
        token = auth['token']
        device_id = auth['device_id']
        print("logged in successfully", file=sys.stderr)
        return token
    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(channel_id):
    headers = {'accept': 'application/json, text/plain, */*', 'authorization': token, 'content-type': 'application/graphql', 'origin': 'https://voyo.rtl.hr', 'referer': 'https://voyo.rtl.hr/tv-uzivo', 'user-agent': USER_AGENT, 'device-id': device_id}
    data = '{ epgHlsUrl(channel: "' + channel_id + '" chunkEnd: 0 chunkStart: 0) { url breaks { from to } } }'
    response = req.post('https://gql.voyo.hr/graphql/?raw', headers=headers, data=data)
    try:
        return response.json()['data']['epgHlsUrl']['url']
    except:
        return None

def get_event(video_id):
    headers = {'accept': 'application/json, text/plain, */*', 'authorization': token, 'content-type': 'application/graphql', 'origin': 'https://voyo.rtl.hr', 'referer': 'https://voyo.rtl.hr/tv-uzivo', 'user-agent': USER_AGENT, 'device-id': device_id}
    data = '{ videoUrl( id: ' + str(video_id) + ' siteId: 30005) { url info infoCode license } }'
    response = req.post('https://gql.voyo.hr/graphql/?raw', headers=headers, data=data)
    try:
        return response.json()['data']['videoUrl']['url']
    except:
        return None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        headers = {'accept': 'application/json, text/plain, */*', 'authorization': token, 'content-type': 'application/graphql', 'origin': 'https://voyo.rtl.hr', 'referer': 'https://voyo.rtl.hr/tv-uzivo', 'user-agent': USER_AGENT, 'device-id': device_id}
        data = '{ epgChannels { channels { channelId name isAVOD image icon } } }'
        response = req.post('https://gql.voyo.hr/graphql/?raw', headers=headers, data=data)
        try:
            resp_data = response.json()
            for ch in resp_data.get('data', {}).get('epgChannels', {}).get('channels', []):
                channel = {
                    'Name': ch.get('name', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"ch={ch.get('channelId', '')}",
                    'CdmType': 'none',
                    'UseCdm': False,
                    'Cdm': '',
                    'Video': 'best',
                    'OnDemand': True,
                    'SpeedUp': True,
                }
                output['Channels'].append(channel)
            events_response = req.get('https://gqlc.voyo.hr/graphql/?raw&query=onl_all_full_liveStreams', headers=headers)
            events_data = events_response.json()
            for s in events_data.get('data', {}).get('liveStreams', {}).get('streams', []):
                if s.get('isNowOn'):
                    channel = {
                        'Name': s.get('title', 'Unknown'),
                        'Mode': 'live',
                        'SessionManifest': True,
                        'ManifestScript': f"ev={s.get('mediaId', '')}",
                        '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:
            if id.startswith('ch='):
                channel_id = id.replace('ch=', '')
                video_url = get_single(channel_id)
            elif id.startswith('ev='):
                video_id = id.replace('ev=', '')
                video_url = get_event(video_id)
            else:
                video_url = None
            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("VoyoHr uses unencrypted HLS streams", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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