#!/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 = '/NHL_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/122.0.0.0 Safari/537.36'

headers = {
    'accept': 'application/json, text/plain, */*',
    'origin': 'https://nhltv.nhl.com',
    'user-agent': USER_AGENT,
}

token = ''

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 login():
    global token
    print("logging in...", file=sys.stderr)
    
    tok = get_auth()
    if not tok:
        print("No token found. Please add NHL token to auth file.", file=sys.stderr)
        print("Copy 'token' cookie from https://nhltv.nhl.com/", file=sys.stderr)
        save_auth('')
        sys.exit(1)
    
    token = tok
    print("logged in successfully", file=sys.stderr)
    return tok

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

def get_auth_code(channel_id):
    cookies = {'token': token}
    auth_headers = {**headers, 'content-type': 'application/json', 'referer': f'https://nhltv.nhl.com/en-int/playerpage/{channel_id}', 'x-ott-app-name': 'Website'}
    response = req.post(f'https://nhltv.nhl.com/api/v3/contents/{channel_id}/check-access', cookies=cookies, headers=auth_headers, json={'type': 'nhl'})
    try:
        return response.json()['data']
    except:
        return None

def get_single(channel_id):
    cookies = {'token': token}
    single_headers = {**headers, 'referer': f'https://nhltv.nhl.com/en-int/playerpage/{channel_id}'}
    auth_code = get_auth_code(channel_id)
    if not auth_code:
        return None
    response = req.post(f'https://nhltv.nhl.com/api/v3/contents/{channel_id}/access/hls', params={'authorization_code': auth_code}, cookies=cookies, headers=single_headers)
    try:
        return response.json()['data']['stream']
    except:
        return None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        cookies = {'token': token}
        formatted_date = datetime.datetime.now().strftime("%Y-%m-%d")
        params = {'sort_direction': 'asc', 'date_time_from': f'{formatted_date}T00:00:00+01:00'}
        ch_headers = {**headers, 'referer': 'https://nhltv.nhl.com/en-int/page/home'}
        response = req.get('https://nhltv.nhl.com/api/v2/events', params=params, cookies=cookies, headers=ch_headers)
        try:
            data = response.json()
            for s in data.get('data', []):
                home = s.get('homeCompetitor', {}).get('name', '')
                away = s.get('awayCompetitor', {}).get('name', '')
                title = f"{home} vs {away}"
                for c in s.get('content', []):
                    if c.get('status', {}).get('isLive') and 'clientContentMetadata' in c and len(c.get('clientContentMetadata', [])) > 0:
                        name = title + f" ({c['clientContentMetadata'][0].get('name', '')})"
                        channel = {
                            'Name': name,
                            'Mode': 'live',
                            'SessionManifest': True,
                            'ManifestScript': f"id={c.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("NHL streams are typically unencrypted HLS", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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