#!/usr/bin/env python3
"""Classroom Connector relay. Python 3 standard library only; leaves BLE bridge unchanged.
Run beside the working LOOI bridge:
 python3 classroom_looi_relay.py --site https://classroomconnex.com --bridge http://10.0.0.246:8765
Paste the Settings pairing code at the hidden prompt. Ctrl-C stops the relay.
Pairing codes are not saved to disk and permit only polling/acknowledging this family's
five supported robot actions, never account access or enqueueing robot motions.
"""
import argparse
import getpass
import ipaddress
import json
import time
import urllib.error
import urllib.parse
import urllib.request

ACTIONS = frozenset(('celebrate', 'nod', 'thinking', 'try_again', 'center'))

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

OPENER = urllib.request.build_opener(NoRedirect)

def validate_url(value, local=False):
    parsed = urllib.parse.urlsplit(value)
    if parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('', '/'):
        raise ValueError('Use a base URL without credentials, path, query or fragment.')
    if not parsed.hostname or parsed.scheme not in (('http', 'https') if local else ('https',)):
        raise ValueError('Use HTTPS for the Classroom Connector site and HTTP or HTTPS for the local bridge.')
    if local and parsed.hostname != 'localhost':
        address = ipaddress.ip_address(parsed.hostname)
        if not (address.is_loopback or any(address in network for network in (ipaddress.ip_network('10.0.0.0/8'), ipaddress.ip_network('172.16.0.0/12'), ipaddress.ip_network('192.168.0.0/16')))):
            raise ValueError('The bridge must use localhost or a private LAN IP address.')
    return value.rstrip('/')

def request_json(url, data, token=None, method='POST', timeout=10):
    headers = {'Accept': 'application/json', 'User-Agent': 'ClassroomConnex-LOOI-Relay/1.1'}
    if data is not None:
        headers['Content-Type'] = 'application/json'
    if token:
        headers['Authorization'] = 'Bearer ' + token
    request = urllib.request.Request(url, data=None if data is None else json.dumps(data).encode(), headers=headers, method=method)
    with OPENER.open(request, timeout=timeout) as response:
        raw = response.read(65536)
        if not raw:
            return {}
        try:
            return json.loads(raw)
        except (ValueError, UnicodeDecodeError):
            return {}

def send_motion(bridge, command, method='auto'):
    if command not in ACTIONS:
        raise ValueError('Unsupported robot action.')
    # POST {} is the default. Only a method-not-supported response permits GET;
    # timeouts and other failures never trigger a duplicate robot action.
    try:
        result = request_json(bridge + '/looi/' + command, None if method == 'GET' else {}, method='GET' if method == 'GET' else 'POST', timeout=8)
    except urllib.error.HTTPError as error:
        if method != 'auto' or error.code not in (405, 501):
            raise
        result = request_json(bridge + '/looi/' + command, None, method='GET', timeout=8)
    if isinstance(result, dict) and (result.get('ok') is False or result.get('success') is False or result.get('status') == 'error'):
        raise ValueError('Bridge reported that the action failed.')

def run(site, bridge, token, method='auto'):
    endpoint = site + '/api/looi/relay'
    print('Relay started. Keep your existing LOOI bridge running. Ctrl-C to stop.', flush=True)
    pending_result = None
    error_shown = False
    connected_once = False
    while True:
        try:
            if pending_result:
                request_json(endpoint, pending_result, token)
                pending_result = None
            response = request_json(endpoint, {'action': 'poll'}, token)
            if not connected_once:
                print('Connected to Classroom Connex. Waiting for a test button or lesson answer.', flush=True)
                connected_once = True
            elif error_shown:
                print('Relay reconnected.', flush=True)
            error_shown = False
            command = response.get('command')
            if command and command.get('command') in ACTIONS and command.get('expires', 0) > time.time()*1000:
                action = command['command']
                try:
                    send_motion(bridge, action, method)
                    status = 'done'
                    print(action + ': bridge accepted the action.', flush=True)
                except (urllib.error.URLError, TimeoutError, ValueError, OSError):
                    status = 'failed'
                    print(action + ': bridge unavailable or action failed. Check the bridge terminal.', flush=True)
                # Retry only result delivery, never the physical motion.
                pending_result = {'action': 'result', 'id': command['id'], 'status': status}
                request_json(endpoint, pending_result, token)
                pending_result = None
            time.sleep(1.5)
        except urllib.error.HTTPError as error:
            if error.code == 401:
                print('Pairing expired or was removed. Create a new code in Settings and restart the relay.', flush=True)
                return
            if not error_shown:
                if error.code == 403:
                    print('Site rejected the relay request (HTTP 403). Stop with Ctrl-C and download the latest relay.', flush=True)
                else:
                    print('Site request failed (HTTP ' + str(error.code) + '). The relay will reconnect; no motions are replayed.', flush=True)
            error_shown = True
            time.sleep(5)
        except (urllib.error.URLError, TimeoutError, ValueError, OSError):
            if not error_shown:
                print('Cannot reach Classroom Connector. Check the Mac internet connection.', flush=True)
            error_shown = True
            time.sleep(5)

def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--site', default='https://classroomconnex.com')
    parser.add_argument('--bridge', default='http://10.0.0.246:8765')
    parser.add_argument('--method', choices=('auto', 'POST', 'GET'), default='auto')
    args = parser.parse_args()
    try:
        site, bridge = validate_url(args.site), validate_url(args.bridge, local=True)
        token = getpass.getpass('Paste the pairing code from Settings (hidden): ').strip()
        if len(token) != 72 or any(c not in '0123456789abcdef-' for c in token):
            raise ValueError('Paste the complete pairing code from Classroom Connector Settings.')
        run(site, bridge, token, args.method)
    except ValueError as error:
        parser.error(str(error))
    except KeyboardInterrupt:
        print('\nRelay stopped. The existing LOOI bridge was left running.')

if __name__ == '__main__':
    main()
