"""Foreground opt-in client. Sends presence only; no jobs, keys, or file uploads."""
import argparse
import getpass
import json
import threading
from urllib.parse import urlsplit
from urllib.request import Request, build_opener, HTTPRedirectHandler
from urllib.error import URLError


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, *_):
        return None


def endpoint(value):
    url = urlsplit(value)
    if (url.username or url.password or url.query or url.fragment or
            url.path not in ('', '/') or not url.hostname):
        raise ValueError('Use a coordinator origin without credentials or a path')
    if url.scheme != 'https' and not (url.scheme == 'http' and
            url.hostname in ('localhost', '127.0.0.1', '::1')):
        raise ValueError('Remote coordinators require HTTPS')
    return value.rstrip('/')


class Client:
    def __init__(self, origin):
        self.origin = endpoint(origin)
        self.opener = build_opener(NoRedirect())

    def call(self, action, token, data=None):
        req = Request(self.origin + '/' + action,
                      data=json.dumps(data or {}).encode(),
                      headers={'Authorization': 'Bearer ' + token,
                               'Content-Type': 'application/json'}, method='POST')
        with self.opener.open(req, timeout=5) as response:
            body = response.read(8193)
            if len(body) > 8192:
                raise ValueError('Coordinator response too large')
            return json.loads(body)


def run(origin):
    client = Client(origin)
    print('INVICTUS NODES — presence-only pilot')
    print('Shares a random node ID, consent and heartbeat times with ' + origin)
    print('No compute, storage, mining, wallet access, startup service or rewards.')
    if input('I own this device or have administrator permission. Type JOIN: ') != 'JOIN':
        print('Not connected.')
        return
    invitation = getpass.getpass('Operator invitation: ')
    joined = client.call('join', invitation, {'consentVersion': 1,
                         'authorizedDevice': True, 'presenceOnly': True})
    token = joined['token']  # In memory only; never written to disk.
    invitation = None
    stop = threading.Event()
    paused = threading.Event()
    lock = threading.Lock()

    def heartbeat():
        while not stop.wait(30):
            with lock:
                if paused.is_set():
                    continue
                try:
                    client.call('heartbeat', token)
                except (URLError, OSError, ValueError):
                    print('Coordinator unavailable; no work is running.')

    worker = threading.Thread(target=heartbeat, daemon=True)
    worker.start()
    print('Connected. Commands: pause, resume, status, disconnect')
    try:
        while True:
            command = input('node> ').strip().lower()
            if command in ('disconnect', 'quit'):
                break
            if command not in ('pause', 'resume', 'status'):
                print('Use pause, resume, status or disconnect.')
                continue
            with lock:
                if command == 'pause':
                    paused.set()  # Local stop works even if coordinator is offline.
                try:
                    result = client.call(command, token)
                    if command == 'resume':
                        paused.clear()
                    print(json.dumps(result))
                except (URLError, OSError, ValueError):
                    print('Coordinator unavailable. Local pause remains effective.')
    except (EOFError, KeyboardInterrupt):
        pass
    finally:
        stop.set()
        worker.join(timeout=6)
        try:
            client.call('leave', token)
            print('Disconnected; node credential revoked.')
        except (URLError, OSError, ValueError):
            print('Stopped locally. Remote record becomes offline within 90 seconds.')


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--coordinator', default='http://127.0.0.1:8130')
    args = parser.parse_args()
    try:
        run(args.coordinator)
    except (URLError, OSError, ValueError, KeyError):
        raise SystemExit('Connection failed. Check the coordinator and invitation.')
