#!/usr/bin/python3
import sys
import os
import base64
import json
import datetime
import pytz
from zoneinfo import ZoneInfo
from datetime import timedelta

# 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 = '/BigTenPlus_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/126.0.0.0 Safari/537.36'

headers = {
    'accept': 'application/json, text/plain, */*',
    'referer': 'https://www.bigtenplus.com/',
    'user-agent': USER_AGENT,
    'x-ott-app-name': 'Website',
}

token = ''
csid = ''

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):
    cookies = {'token': tok}
    response = req.get('https://www.bigtenplus.com/api/v3/cleeng/profile', cookies=cookies, headers=headers)
    response.raise_for_status()
    return response.json()['id']

def login():
    global token, csid
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'token' not in auth:
        print("No auth found. Please add BigTenPlus token to auth file.", file=sys.stderr)
        print("Login to https://www.bigtenplus.com and copy 'token' cookie value", file=sys.stderr)
        save_auth({'token': 'ENTER_TOKEN_HERE'})
        sys.exit(1)
    
    try:
        csid = check_token(auth['token'])
        token = auth['token']
        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 generate_range_strings(tz='Europe/Berlin'):
    now = datetime.datetime.now(ZoneInfo(tz))
    start = (now - timedelta(days=1)).replace(hour=12, minute=0, second=0, microsecond=0)
    end = (now + timedelta(days=1)).replace(hour=11, minute=59, second=59, microsecond=0)
    return start.isoformat(), end.isoformat()

def range_strings_today(tz='Europe/Berlin'):
    now = datetime.datetime.now(ZoneInfo(tz))
    start = now.replace(hour=0, minute=0, second=0, microsecond=0)
    end = now.replace(hour=23, minute=59, second=59, microsecond=0)
    return start.isoformat(), end.isoformat()

def check_access(content_id):
    cookies = {'token': token}
    response = req.post(f'https://www.bigtenplus.com/api/v3/contents/{content_id}/check-access', cookies=cookies, headers=headers, json={'type': 'cleeng'})
    try:
        return response.json()['data']
    except:
        return None

def get_single(content_id, request_token):
    cookies = {'token': token}
    params = {'csid': csid, 'authorization_code': request_token}
    response = req.post(f'https://www.bigtenplus.com/api/v3/contents/{content_id}/access/hls', params=params, cookies=cookies, headers=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}
        
        # Get channel IDs
        params = {'language_id': '245'}
        response = req.get('https://www.bigtenplus.com/api/page/data/9694', params=params, cookies=cookies, headers=headers)
        
        try:
            data = response.json()
            channel_ids = [c['id'] for c in data['data']['modules'][0]['epgChannels']]
            
            start_str, end_str = generate_range_strings()
            
            json_data = {
                'operationName': None,
                'variables': {'portalId': 277, 'languageId': 245, 'channelIds': channel_ids, 'from': start_str, 'to': end_str},
                'query': 'query ($portalId: Int!, $languageId: Int!, $channelIds: [Int], $from: DateTimeTz!, $to: DateTimeTz!) { epgChannels(channelIds: $channelIds, portalId: $portalId) { id displayName assets(start: {from: $from, to: $to}) { start end baseConfigEventContent { id } } } }'
            }
            
            response = req.post('https://www.bigtenplus.com/api/graphql', cookies=cookies, headers=headers, json=json_data)
            data = response.json()
            
            for ch in data['data'].get('epgChannels', []):
                channel = {
                    'Name': ch.get('displayName', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={json.dumps(ch)}",
                    'CdmType': 'none',
                    'UseCdm': False,
                    'Cdm': '',
                    'Video': 'best',
                    'OnDemand': True,
                    'SpeedUp': True,
                }
                output['Channels'].append(channel)
            
            # Get events
            start_str, end_str = range_strings_today()
            params = {'filter[deviceCategory]': '1', 'filter[dateTimeFrom]': start_str, 'filter[dateTimeTo]': end_str, 'limit': '100', 'page': '1'}
            response = req.get('https://www.bigtenplus.com/api/v3/modules/138951/contents', params=params, cookies=cookies, headers=headers)
            data = response.json()
            
            tz = 'Europe/Berlin'
            now = datetime.datetime.now(ZoneInfo(tz))
            
            for e in data.get('data', []):
                try:
                    start = datetime.datetime.fromisoformat(e['startTime']).replace(tzinfo=ZoneInfo('UTC'))
                    start_local = start.astimezone(ZoneInfo(tz))
                    if start_local <= now and e['contents'][0]['distributionType']['name'].lower() == 'live':
                        category = e.get('category3', {}).get('name', '')
                        away = e.get('awayCompetitor', {}).get('name', '')
                        home = e.get('homeCompetitor', {}).get('name', '')
                        name = f'{category} {away} - {home}'
                        channel = {
                            'Name': name,
                            'Mode': 'live',
                            'SessionManifest': True,
                            'ManifestScript': f"id={e['contents'][0]['id']}",
                            'CdmType': 'none',
                            'UseCdm': False,
                            'Cdm': '',
                            'Video': 'best',
                            'OnDemand': True,
                            'SpeedUp': True,
                        }
                        output['Channels'].append(channel)
                except:
                    pass
            
            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:
            content_id = id
            # Check if it's a channel object or direct content ID
            try:
                ch_data = json.loads(id)
                # Find current content from channel assets
                tz = 'Europe/Berlin'
                now = datetime.datetime.now(ZoneInfo(tz))
                for asset in ch_data.get('assets', []):
                    start = datetime.datetime.strptime(asset['start'], '%Y-%m-%d %H:%M:%S').replace(tzinfo=ZoneInfo('UTC'))
                    end = datetime.datetime.strptime(asset['end'], '%Y-%m-%d %H:%M:%S').replace(tzinfo=ZoneInfo('UTC'))
                    if start.astimezone(ZoneInfo(tz)) <= now <= end.astimezone(ZoneInfo(tz)):
                        content_id = asset['baseConfigEventContent']['id']
                        break
            except:
                pass
            
            request_token = check_access(content_id)
            if not request_token:
                return "error"
            
            video_url = get_single(content_id, request_token)
            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("BigTenPlus streams are typically unencrypted HLS", file=sys.stderr)
    
    else:
        print("invalid action: " + action, file=sys.stderr)

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