#!/usr/bin/python3
import sys
import os
import base64
import json
import datetime
import pytz
import time
import uuid
import hashlib
from urllib.parse import unquote

# 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 = '/GoNetTV_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 request_token(auth_cookie):
    headers = {'accept': 'application/json, text/javascript, */*; q=0.01', 'origin': 'https://www.gonet.tv', 'referer': 'https://www.gonet.tv/onlinetv/', 'user-agent': USER_AGENT}
    params = {'auth': unquote(auth_cookie), 'zarizeni': '', 'auth_android_tvpcz': '', 'zarizeni_id': ''}
    response = req.get('https://www6.gonet.tv/api/obnovit_login.php', params=params, headers=headers)
    return response.cookies.get_dict()['key']

def login():
    global token, device_id
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'auth_cookie' not in auth:
        print("No auth found. Please add GoNetTV auth_cookie to auth file.", file=sys.stderr)
        save_auth({'auth_cookie': '', 'device_id': str(uuid.uuid4())})
        sys.exit(1)
    
    try:
        token = request_token(auth['auth_cookie'])
        device_id = auth.get('device_id', str(uuid.uuid4()))
        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_u_value(channel_id, stream_domain):
    headers = {'accept': 'text/plain, */*; q=0.01', 'referer': 'https://www.gonet.tv/onlinetv/', 'user-agent': USER_AGENT, 'x-requested-with': 'XMLHttpRequest'}
    params = {'auth': token, 'profil': '', 'path': '/onlinetv/', 'token': '', 'server': stream_domain, 'stanice': channel_id, 'verze': '236', 'zarizeni': '', 'zarizeni_id': device_id, 'zarizeni_model': ''}
    response = req.get('https://www.gonet.tv/api/overeniP.php', params=params, headers=headers)
    try:
        data = response.content.decode()
        u_parts = data.split(':')
        return u_parts[0], u_parts[1]
    except:
        return None, None

def get_single(channel_id):
    headers = {'accept': 'application/json, text/javascript, */*; q=0.01', 'referer': 'https://www.gonet.tv/onlinetv/?lang=hr&s=138', 'user-agent': USER_AGENT, 'x-requested-with': 'XMLHttpRequest'}
    params = {'auth': token, 'profil': '', 'k': '1', 'c': 'h265', 'zarizeni': '', 'verze': '20', 'obr_ctverce': '1', 'disable_hbomax': '1', 's': channel_id, 'porad': '', 'tdif': '1', 'force_stream': '', 'sl': 'false'}
    response = req.get('https://www.gonet.tv/api/program0.php', params=params, headers=headers)
    try:
        data = response.json()
        porad_id = None
        offset = None
        current_millis = int(time.time())
        porady = list(data.values())[0]['porady']
        for v in porady.values():
            time_start = v['casodRT']
            time_end = v['casdoRT']
            if time_start <= current_millis <= time_end:
                porad_id = v['id']
                offset = str(v['stream-'])
                break
        if not porad_id or not offset:
            return None
        params['porad'] = porad_id
        response = req.get('https://www.gonet.tv/api/program0.php', params=params, headers=headers)
        data = response.json()
        url = unquote(data['stream']['auto'])
        stream_domain = url.split('/')[2]
        u_value, u_timestamp = get_u_value(channel_id, stream_domain)
        if not u_value or not u_timestamp:
            return None
        utc_time = datetime.datetime.utcfromtimestamp(int(u_timestamp))
        target_tz = pytz.timezone('Europe/Zagreb')
        local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(target_tz)
        formatted_time = local_time.strftime('%Y-%m-%d %H:%M:%S')
        url = url.replace('@OFFSET@', offset).replace('@TT@', formatted_time) + '&u=' + u_value + '&a='
        return 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/javascript, */*; q=0.01', 'referer': 'https://www.gonet.tv/onlinetv/', 'user-agent': USER_AGENT, 'x-requested-with': 'XMLHttpRequest'}
        params = {'auth': token, 'profil': '', 'k': '1', 'c': 'h265', 'zarizeni': '', 'verze': '20', 'obr_ctverce': '1', 'disable_hbomax': '0', 'r[0][stations]': '1', 'r[1][preklady]': '1', 'r[2][radia]': '1', 'r[2][radia_pocet]': '1'}
        response = req.get('https://www.gonet.tv/api/program0.php', params=params, headers=headers)
        try:
            data = response.json()
            for ch in data[0]:
                channel = {
                    'Name': ch.get('stanice', 'Unknown').replace(':D', ''),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={ch.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:
            channel_id = id
            video_url = get_single(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("GoNetTV uses unencrypted HLS streams", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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