#!/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 = '/Cariflix_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/138.0.0.0 Safari/537.36'
RESELLER_ID = '56b3765be4b0b76386bab72f'
LOGIN_TOKEN = 'NjZiNzQxOTQ0OTM5NzAxMjI3YjQ1YjYwODFkN2UwOWQ4MWFiMTdkNGQ4OGQ0YzIyODAzNjgwMDYwMWE2OjI0ODY2YTcwYzUyNjY4ZmYxODE5Zjk5YjA3MGFkNWU2NmIyNjAzNzY5OTM4NmQ4Y2FjMmFmOTYwNjA2NQ=='

headers = {
    'accept': 'application/json, text/plain, */*',
    'origin': 'https://www.cariflix.com',
    'referer': 'https://www.cariflix.com/',
    'user-agent': USER_AGENT,
    'x-app-name': 'cariflix',
    'x-app-platform': 'web',
    'x-app-version': '0.0.0',
    'x-langcode': 'en',
    'x-os-version': 'Chrome 138',
}

token = ''

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(refresh_token):
    refresh_headers = {**headers, 'authorization': 'Basic ' + LOGIN_TOKEN, 'content-type': 'application/x-www-form-urlencoded'}
    data = {'grant_type': 'refresh_token', 'refresh_token': refresh_token, 'scope': 'services', 'reseller_id': RESELLER_ID}
    response = req.post('https://api.streann.tech/web/oauth/token', params={'r': RESELLER_ID}, headers=refresh_headers, data=data)
    result = response.json()
    return result['access_token'], result['refresh_token']

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'refresh_token' not in auth:
        print("No auth found. Please add Cariflix refresh_token to auth file.", file=sys.stderr)
        print("Login to https://www.cariflix.com/ and copy refresh_token from Local Storage", file=sys.stderr)
        save_auth({'refresh_token': ''})
        sys.exit(1)
    
    try:
        tok, new_refresh = do_refresh(auth['refresh_token'])
        save_auth({'refresh_token': new_refresh})
        token = tok
        print("logged in successfully", file=sys.stderr)
        return tok
    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):
    params = {'access_token': token, 'device-type': 'web', 'device-name': 'web', 'withCredentials': 'false', 'doNotUseRedirect': 'true', 'langCode': 'en', 'country_code': 'AW', 'r': RESELLER_ID}
    response = req.get(f'https://api.streann.tech/loadbalancer/services/v1/channels-secure/{channel_id}/playlist.m3u8', params=params, headers=headers)
    try:
        return response.json()['url']
    except:
        return None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        ch_headers = {**headers, 'authorization': 'Bearer ' + token}
        params = {'dt': 'web', 'ln': 'en', 'cc': 'AW', 'r': RESELLER_ID}
        response = req.get('https://api.streann.tech/web/services/v3/user/tab-layout', params=params, headers=ch_headers)
        try:
            data = response.json()
            channels = []
            for l in data.get('layouts', []):
                for ca in l.get('categories', []):
                    if ca.get('type') == 'channel':
                        for co in ca.get('content', []):
                            if co.get('type') == 'channel':
                                channels.append(co)
            channels = list({item['id']: item for item in channels}.values())
            for ch in channels:
                channel = {
                    'Name': ch.get('name', 'Unknown'),
                    '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("Cariflix streams are typically unencrypted HLS", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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