#!/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 = '/MOVETV_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/136.0.0.0 Safari/537.36'

token = ''
customer_id = ''
customer_profile_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 do_refresh(profile_id, refresh_token):
    headers = {'accept': '*/*', 'content-type': 'application/json', 'origin': 'https://play.move.tv', 'referer': 'https://play.move.tv/', 'user-agent': USER_AGENT, 'x-refresh-token': refresh_token}
    json_data = {'customerProfileId': profile_id}
    response = req.post('https://api2.mts-si.tv/api/v2/token/status', headers=headers, json=json_data)
    data = response.json()
    return data['auth_token'], data['refresh_token'], data['customer_id']

def login():
    global token, customer_id, customer_profile_id
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'refresh_token' not in auth:
        print("No auth found. Please add MOVETV refresh_token and customer_profile_id to auth file.", file=sys.stderr)
        save_auth({'refresh_token': '', 'customer_profile_id': ''})
        sys.exit(1)
    
    try:
        new_token, new_refresh, new_customer_id = do_refresh(auth['customer_profile_id'], auth['refresh_token'])
        save_auth({'refresh_token': new_refresh, 'customer_profile_id': auth['customer_profile_id']})
        token = new_token
        customer_id = new_customer_id
        customer_profile_id = auth['customer_profile_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(live_id):
    headers = {'accept': '*/*', 'content-type': 'application/json', 'origin': 'https://play.move.tv', 'referer': 'https://play.move.tv/', 'user-agent': USER_AGENT, 'x-auth-token': token}
    json_data = {'customerId': customer_id, 'customerProfileId': customer_profile_id, 'liveId': live_id, 'dtype': 1}
    response = req.post('https://api2.mts-si.tv/api/v2/content/live/source/get', headers=headers, json=json_data)
    try:
        data = response.json()
        header_name = None
        header_value = None
        if 'protection' in data and data['protection']['protected']:
            header_name = data['protection']['headerName']
            header_value = data['protection']['headerValue']
        return data['content_url'], header_name, header_value
    except:
        return None, None, None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        headers = {'accept': '*/*', 'content-type': 'application/json', 'origin': 'https://play.move.tv', 'referer': 'https://play.move.tv/', 'user-agent': USER_AGENT, 'x-auth-token': token}
        json_data = {'customerId': customer_id, 'customerProfileId': customer_profile_id}
        response = req.post('https://api2.mts-si.tv/api/v2/content/live/all', headers=headers, json=json_data)
        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:
            live_id = id
            video_url, header_name, header_value = get_single(live_id)
            if not video_url:
                return "error"
            media_headers = {'User-Agent': USER_AGENT}
            if header_name and header_value:
                media_headers[header_name] = header_value
            output = {
                "Cdn": [{"Name": "default", "ManifestUrl": video_url}],
                "ManifestUrl": video_url,
                "Headers": {"Manifest": media_headers, "Media": media_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("MOVETV uses AES-128 encryption, not Widevine CDM", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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