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

# 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 = '/CablevisionPlus_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/123.0.0.0 Safari/537.36'

headers = {
    'accept': 'application/json',
    'content-type': 'application/x-www-form-urlencoded',
    'origin': 'https://www.cvplus.tv',
    'referer': 'https://www.cvplus.tv/',
    'user-agent': USER_AGENT,
    'x-an-webservice-version': '2',
}

token = ''
client_id = ''

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):
    decoded = jwt.decode(tok, options={"verify_signature": False})
    check_headers = {**headers, 'x-an-webservice-customerauthtoken': tok, 'x-an-webservice-identitykey': decoded['client_id']}
    response = req.get('https://proxies.econet.com.lb/crm/profile', headers=check_headers)
    return response.json().get('status', False)

def login():
    global token, client_id
    print("logging in...", file=sys.stderr)
    
    tok = get_auth()
    if not tok:
        print("No token found. Please add CablevisionPlus token to auth file.", file=sys.stderr)
        save_auth('')
        sys.exit(1)
    
    try:
        if check_token(tok):
            token = tok
            decoded = jwt.decode(token, options={"verify_signature": False})
            client_id = decoded['client_id']
            print("logged in successfully", file=sys.stderr)
            return token
        else:
            print("Token invalid or expired", file=sys.stderr)
            sys.exit(1)
    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):
    single_headers = {**headers, 'x-an-webservice-customerauthtoken': token, 'x-an-webservice-identitykey': client_id}
    response = req.post('https://proxies.econet.com.lb/proxy/channelStream', headers=single_headers, data={'idChannel': channel_id})
    try:
        return response.json()['result']['url'].split('?')[0]
    except:
        return None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        ch_headers = {**headers, 'x-an-webservice-identitykey': client_id}
        response = req.post('https://proxies.econet.com.lb/proxy/listChannels', headers=ch_headers, data={'languageId': 'eng'})
        try:
            data = response.json()
            for ch in data.get('result', {}).get('channels', []):
                channel = {
                    'Name': ch.get('name', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={ch.get('idChannel', '')}",
                    '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("CablevisionPlus streams are typically unencrypted HLS", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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