#!/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 = '/MOVETVBosnia_auth.json'
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))

USER_AGENT = 'MOVE/2 CFNetwork/3826.500.131 Darwin/24.5.0'

headers = {
    'accept': '*/*',
    'content-type': 'application/json',
    'user-agent': USER_AGENT,
    'accept-language': 'en-US,en;q=0.9',
    'accept-encoding': 'deflate, gzip',
}

token_data = None

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):
    payload = {'customerProfileId': tok['profile']['id']}
    response = req.post('https://api2.mts-si.tv/api/v2/content/page/static', json=payload, headers={**headers, 'x-auth-token': tok['auth_token']})
    if response.json().get('success') is False or response.status_code != 200:
        raise Exception('Token expired')

def do_login(uname, pwd):
    payload = {'deviceModelId': 7, 'deviceName': 'iPhone16,2', 'uid': '569DEC91-BD31-4DE7-9FC6-228BB86E05E8', 'username': uname, 'partnerId': 4, 'password': pwd}
    response = req.post('https://api2.mts-si.tv/api/v2/login/', json=payload, headers=headers)
    data = response.json()
    if 'auth_token' not in data:
        raise Exception('Login failed')
    return data

def login():
    global token_data
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if auth and 'auth_token' in auth:
        try:
            check_token(auth)
            token_data = auth
            print("logged in successfully", file=sys.stderr)
            return token_data
        except:
            pass
    
    if not auth or 'username' not in auth:
        print("No auth found. Please add MOVETVBosnia credentials to auth file.", file=sys.stderr)
        save_auth({'username': '', 'password': ''})
        sys.exit(1)
    
    try:
        token_data = do_login(auth['username'], auth['password'])
        save_auth(token_data)
        print("logged in successfully", file=sys.stderr)
        return token_data
    except Exception as e:
        print(f"Login failed: {e}", file=sys.stderr)
        sys.exit(1)

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

def get_mpd(channel_id):
    payload = {'customerId': token_data['customer_id'], 'liveId': channel_id, 'dtype': 1, 'customerProfileId': token_data['profile']['id']}
    response = req.post('https://api2.mts-si.tv/api/v2/content/live/source/get', json=payload, headers={**headers, 'x-auth-token': token_data['auth_token']})
    try:
        data = response.json()
        return data.get('content_url'), data.get('protection')
    except:
        return None, None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        payload = {'customerId': token_data['customer_id'], 'customerProfileId': token_data['profile']['id'], 'lang': 2}
        response = req.post('https://api2.mts-si.tv/api/v2/content/live/all', json=payload, headers={**headers, 'x-auth-token': token_data['auth_token']})
        try:
            data = response.json()
            for ch in data.get('content', []):
                channel = {
                    'Name': ch.get('contentName', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={ch.get('liveId', '')}",
                    '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, protection = get_mpd(channel_id)
            if not video_url:
                return "error"
            manifest_headers = {'User-Agent': USER_AGENT}
            if protection:
                header_name = protection.get('headerName', 'X-Play-Auth')
                header_value = protection.get('value', '')
                manifest_headers[header_name] = header_value
            output = {
                "Cdn": [{"Name": "default", "ManifestUrl": video_url}],
                "ManifestUrl": video_url,
                "Headers": {"Manifest": manifest_headers, "Media": manifest_headers},
                "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("MOVETVBosnia uses AES-128 encryption, not Widevine", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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