#!/usr/bin/env python3
"""Forward Condor UDP with optional navigation from the same simulator’s NMEA output."""

import argparse
from contextlib import ExitStack
import errno
import ipaddress
import json
import math
import os
from pathlib import Path
import re
import select
import signal
import socket
import subprocess
import sys
import tempfile
import time


FRESH_SECONDS = 2.0


def condor_time(payload):
    fields = {}
    for line in payload.strip(b'\0').splitlines():
        if not line.strip():
            continue
        key, sep, value = line.partition(b'=')
        key = key.strip()
        if not sep or not key or key in fields or key.startswith(b'nmea_'):
            return None
        fields[key] = value.strip()
    try:
        hours, pitch, bank, compass, altitude = (float(fields[key]) for key in
                                                 (b'time', b'pitch', b'bank', b'compass', b'altitude'))
    except (KeyError, ValueError):
        return None
    if (0 <= hours <= 24 and abs(pitch) <= math.pi and abs(bank) <= 2 * math.pi
            and 0 <= compass <= 360 and math.isfinite(altitude)):
        return hours
    return None


def coordinate_is_valid(value, hemisphere, latitude):
    digits, maximum, directions = (4, 90, (b'N', b'S')) if latitude else (5, 180, (b'E', b'W'))
    integer, decimal_point, fraction = value.partition(b'.')
    if (hemisphere not in directions or len(integer) != digits or not integer.isdigit()
            or (decimal_point and not fraction.isdigit())):
        return False
    degrees, minutes = int(integer[:-2]), float(value[digits - 2:])
    return minutes < 60 and (degrees < maximum or (degrees == maximum and minutes == 0))


def utc_seconds(value):
    if not re.fullmatch(rb'\d{6}(?:\.\d+)?', value):
        return None
    hours, minutes, seconds = int(value[:2]), int(value[2:4]), float(value[4:])
    return hours * 3600 + minutes * 60 + seconds if hours < 24 and minutes < 60 and seconds < 60 else None


def usable_gga(fields):
    if not (len(fields) == 15 or (len(fields) == 16 and not fields[14])):
        return False
    unsigned = rb'\d+(?:\.\d+)?'
    signed = rb'[+-]?' + unsigned
    if ((fields[7] and not fields[7].isdigit()) or (fields[8] and not re.fullmatch(unsigned, fields[8]))
            or not re.fullmatch(signed, fields[9]) or fields[12] not in (b'', b'M')
            or (fields[11] and (not re.fullmatch(signed, fields[11]) or fields[12] != b'M'))
            or (fields[13] and not re.fullmatch(unsigned, fields[13]))):
        return False
    if (fields[6] not in (b'1', b'2', b'3', b'4', b'5') or fields[10] != b'M'
            or not coordinate_is_valid(fields[2], fields[3], True)
            or not coordinate_is_valid(fields[4], fields[5], False)):
        return False
    try:
        return math.isfinite(float(fields[9]))
    except ValueError:
        return False


class CondorNavigation:
    def __init__(self, offset):
        self.offset = offset
        self.disconnect()

    def disconnect(self):
        self.source = None
        self.last_udp = None
        self.sim_hours = None
        self.sim_advanced = None
        self.clear_fix()
        self.last_epoch = None
        self.buffer = b''
        self.discard_line = False

    def clear_fix(self):
        self.gga = None
        self.lxwp = None
        self.raw_heading = None

    def feed(self, data, now):
        for chunk in data.replace(b'\r', b'\n').splitlines(keepends=True):
            complete = chunk.endswith(b'\n')
            if not self.discard_line:
                self.buffer += chunk.rstrip(b'\n')
                if len(self.buffer) > 160:
                    self.discard_line = True
                elif complete and self.buffer:
                    self.sentence(self.buffer, now)
            if complete or self.discard_line:
                self.buffer = b''
            if complete:
                self.discard_line = False

    def sentence(self, line, now):
        if self.last_udp is None or now - self.last_udp > FRESH_SECONDS:
            return
        if not line.startswith((b'$GPGGA,', b'$GNGGA,', b'$LXWP0,')):
            return
        body, _, checksum = line[1:].partition(b'*')
        if not re.fullmatch(rb'[0-9A-Fa-f]{2}', checksum) or b'$' in body or not all(32 <= c <= 126 for c in body):
            return
        value = 0
        for c in body:
            value ^= c
        if value != int(checksum, 16):
            return
        fields = body.split(b',')
        if fields[0] == b'LXWP0':
            try:
                heading = float(fields[10])
            except (IndexError, ValueError):
                heading = None
            self.lxwp = (line, now) if heading is not None and 0 <= heading <= 360 else None
            self.raw_heading = heading if self.lxwp else None
            return
        epoch = utc_seconds(fields[1])
        usable = epoch is not None and usable_gga(fields)
        if not usable:
            self.clear_fix()
        if epoch is None:
            return
        if self.last_epoch is not None:
            delta = (epoch - self.last_epoch) % 86400
            if delta == 0 or delta > 43200:
                return
        self.last_epoch = epoch
        if usable:
            self.gga = (line, now)

    @staticmethod
    def age(sample, now):
        if sample is not None and 0 <= now - sample[1] < FRESH_SECONDS:
            return math.ceil((now - sample[1]) * 1000)
        return None

    def enrich(self, payload, source, now):
        hours = condor_time(payload)
        if hours is None:
            return payload
        if self.source is not None and self.source != source:
            if now - self.last_udp < FRESH_SECONDS:
                return payload
            # Condor may reopen its UDP socket while keeping the virtual COM port open.
            self.disconnect()
        if self.last_udp is None or now - self.last_udp >= FRESH_SECONDS:
            self.clear_fix()
            self.sim_hours = None
        elif self.sim_hours is not None and (hours - self.sim_hours) % 24 > 12:
            # A flight restarted on the same socket; wait for navigation from the new flight.
            self.clear_fix()
            self.last_epoch = None
        self.source = source
        if self.sim_hours != hours:
            if self.sim_advanced is not None and now - self.sim_advanced >= FRESH_SECONDS:
                self.clear_fix()
            self.sim_advanced = now
        self.sim_hours = hours
        self.last_udp = now
        age = self.age(self.gga, now)
        if age is None or now - self.sim_advanced >= FRESH_SECONDS:
            return payload
        fields = [b'nmea_gga=' + self.gga[0], b'nmea_gga_age_ms=' + str(age).encode()]
        heading_age = self.age(self.lxwp, now)
        if heading_age is not None:
            fields += [b'nmea_lxwp0=' + self.lxwp[0], b'nmea_lxwp0_age_ms=' + str(heading_age).encode()]
            if self.offset is not None:
                fields.append(b'nmea_heading_offset_deg=' + str(self.offset).encode())
        body = payload.rstrip(b'\0')
        separator = b'' if body.endswith((b'\n', b'\r')) else b'\r\n'
        extra = separator + b'\r\n'.join(fields) + b'\r\n'
        if len(payload) + len(extra) > 65507:
            return payload
        return body + extra + payload[len(body):]

    def status(self, now):
        fix = self.age(self.gga, now) is not None
        heading = self.raw_heading if self.age(self.lxwp, now) is not None else None
        return fix, heading


class NMEAInput:
    def __init__(self, args, stack, state):
        self.navigation = CondorNavigation(args.heading_offset_deg)
        self.terminal = sys.stdin if os.name == 'posix' and sys.stdin.isatty() else None
        self.listener = None
        self.client = None
        self.tty_fd = None
        self.serial_path = args.nmea_serial
        self.baud = args.nmea_baud
        self.read_after = 0
        if args.nmea_tcp_port is not None:
            self.listener = stack.enter_context(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
            self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.listener.bind(('127.0.0.1', args.nmea_tcp_port))
            self.listener.listen(1)
            state['nmea_tcp_port'] = self.listener.getsockname()[1]
            stack.callback(self.close_client)
            print(f"NMEA: listening on TCP 127.0.0.1:{state['nmea_tcp_port']}", flush=True)
        elif args.nmea_pty is not None:
            import tty
            master, slave = os.openpty()
            stack.callback(os.close, master)
            try:
                tty.setraw(slave)
                device = os.ttyname(slave)
                args.nmea_pty.symlink_to(device)
            finally:
                os.close(slave)
            def remove_link():
                if args.nmea_pty.is_symlink() and os.readlink(args.nmea_pty) == device:
                    args.nmea_pty.unlink()
            stack.callback(remove_link)
            self.tty_fd = master
            os.set_blocking(master, False)
            print(f'NMEA: map the Condor COM output to {args.nmea_pty.absolute()} ({device})', flush=True)
        else:
            self.open_serial()
            stack.callback(self.close_serial)
        print('The relay needs a single local Condor instance for both UDP and NMEA.', flush=True)
        if self.terminal is not None:
            print('To calibrate, type true runway bearing minus the stationary LXWP0 nose heading, then press Return.',
                  flush=True)
        print(f"Heading offset: {self.navigation.offset if self.navigation.offset is not None else 'not set'}", flush=True)

    def open_serial(self):
        import termios
        import tty
        fd = os.open(self.serial_path, os.O_RDONLY | os.O_NOCTTY | os.O_NONBLOCK)
        try:
            self.original_mode = termios.tcgetattr(fd)
            tty.setraw(fd)
            options = termios.tcgetattr(fd)
            options[4] = options[5] = getattr(termios, f'B{self.baud}')
            termios.tcsetattr(fd, termios.TCSANOW, options)
        except (OSError, termios.error):
            os.close(fd)
            raise
        self.tty_fd = fd
        print(f'NMEA: reading {self.serial_path} at {self.baud} baud', flush=True)

    def close_serial(self):
        import termios
        if self.tty_fd is not None:
            try:
                termios.tcsetattr(self.tty_fd, termios.TCSANOW, self.original_mode)
            except (OSError, termios.error):
                pass
            os.close(self.tty_fd)
            self.tty_fd = None

    def close_client(self):
        if self.client:
            self.client.close()
            self.client = None

    def readers(self, now):
        if self.serial_path is not None and self.tty_fd is None and now >= self.read_after:
            import termios
            try:
                self.open_serial()
            except (OSError, termios.error):
                self.read_after = now + 1
        result = [item for item in (self.listener, self.client, self.terminal) if item is not None]
        if self.tty_fd is not None and now >= self.read_after:
            result.append(self.tty_fd)
        return result

    def read(self, reader, now):
        if reader is self.terminal:
            line = reader.readline()
            if not line:
                self.terminal = None
                return
            try:
                offset = float(line.strip())
                if not -180 <= offset <= 180:
                    raise ValueError
            except ValueError:
                print('Enter a signed heading offset in degrees between -180 and 180.', flush=True)
                return
            self.navigation.offset = offset
            print(f'Active heading offset: {offset:+g}°. To reuse it, start with --heading-offset-deg {offset:g}.',
                  flush=True)
            return
        if reader is self.listener:
            connection, _ = self.listener.accept()
            if self.client is None:
                self.client = connection
            else:
                connection.close()
            return
        try:
            data = os.read(reader, 4096) if reader == self.tty_fd else reader.recv(4096)
        except BlockingIOError:
            return
        except OSError as error:
            if error.errno not in (errno.EIO, errno.ENXIO, errno.ENODEV, errno.ECONNRESET, errno.ENOTCONN):
                raise
            data = b''
        if data:
            self.navigation.feed(data, now)
        else:
            if reader == self.tty_fd:
                # A PTY master reports EOF while no application has its slave open.
                self.read_after = now + 0.25
                if self.serial_path is not None:
                    self.close_serial()
            else:
                self.close_client()
            self.navigation.disconnect()


def save_status(path, state):
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(path.name + '.tmp')
    temporary.write_text(json.dumps(state, indent=2) + '\n')
    temporary.replace(path)


def forward(args):
    state = {
        'state': 'starting', 'pid': os.getpid(),
        'destination': f'{args.host}:{args.port}',
        'received': 0, 'sent_to_os': 0, 'send_errors': 0,
        'last_packet_at': None, 'last_sent_at': None,
    }

    def stop(signum, frame):
        raise KeyboardInterrupt

    signal.signal(signal.SIGTERM, stop)
    last_report = 0
    last_packet = None
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as receiver, \
            socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender, ExitStack() as stack:
        try:
            receiver.bind(('127.0.0.1', args.listen_port))
        except OSError as error:
            raise SystemExit(f'Cannot listen on 127.0.0.1:{args.listen_port}: {error}. '
                             'Close the other relay before starting this one.')
        uses_nmea = args.nmea_tcp_port is not None or args.nmea_serial is not None or args.nmea_pty is not None
        nmea = NMEAInput(args, stack, state) if uses_nmea else None
        sender.settimeout(1)
        state['listen'] = f'127.0.0.1:{receiver.getsockname()[1]}'
        state['state'] = 'listening'
        save_status(args.status, state)
        print(f"Condor UDP: {state['listen']} -> {state['destination']}", flush=True)
        print('Keep this Terminal window open. Stop with Control-C.', flush=True)
        print('This relay never changes UDP.ini. Waiting for simulator packets...', flush=True)
        try:
            while True:
                readers = nmea.readers(time.monotonic()) if nmea else []
                ready, _, _ = select.select(readers + [receiver], [], [], 0.25)
                if nmea:
                    for reader in ready:
                        if reader is not receiver:
                            nmea.read(reader, time.monotonic())
                if receiver in ready:
                    payload, source = receiver.recvfrom(65535)
                    if nmea:
                        payload = nmea.navigation.enrich(payload, source, time.monotonic())
                    state['received'] += 1
                    last_packet = time.monotonic()
                    state['last_packet_at'] = time.time()
                    state['source'] = f'{source[0]}:{source[1]}'
                    try:
                        count = sender.sendto(payload, (args.host, args.port))
                        if count != len(payload):
                            raise OSError('Incomplete UDP send')
                        state['sent_to_os'] += 1
                        state['last_sent_at'] = time.time()
                        state.pop('current_send_error', None)
                    except OSError as error:
                        state['send_errors'] += 1
                        state['current_send_error'] = str(error)
                now = time.monotonic()
                if now - last_report >= 1:
                    state['updated_at'] = time.time()
                    state['last_packet_age_seconds'] = None if last_packet is None else round(now - last_packet, 2)
                    nmea_report = ''
                    if nmea:
                        fix, heading = nmea.navigation.status(now)
                        state['nmea_heading_offset_deg'] = nmea.navigation.offset
                        state['nmea_fix'] = fix
                        state['nmea_raw_heading_deg'] = heading
                        heading_text = 'waiting' if heading is None else f'{heading:g}°'
                        nmea_report = f" | NMEA fix: {'yes' if fix else 'waiting'} | LXWP0 nose: {heading_text}"
                    save_status(args.status, state)
                    if state['received']:
                        detail = state.get('current_send_error', 'waiting for packets' if now - last_packet > 2 else 'sending')
                        print(f"Received: {state['received']} | Sent: {state['sent_to_os']} | "
                              f"Errors: {state['send_errors']} | {detail}{nmea_report}", flush=True)
                    last_report = now
        except KeyboardInterrupt:
            pass
        finally:
            state['state'] = 'stopped'
            state['updated_at'] = time.time()
            save_status(args.status, state)
            print('Relay stopped. UDP.ini was not changed.', flush=True)


def self_test():
    with tempfile.TemporaryDirectory(prefix='airhorizon-relay-test-') as directory, \
            socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as phone, \
            socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as simulator:
        phone.bind(('127.0.0.1', 0))
        phone.settimeout(3)
        status = Path(directory) / 'status.json'
        process = subprocess.Popen([
            sys.executable, str(Path(__file__).resolve()), '--host', '127.0.0.1',
            '--listen-port', '0', '--port', str(phone.getsockname()[1]), '--status', str(status)
        ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
        try:
            deadline = time.monotonic() + 15
            while not status.exists():
                if process.poll() is not None or time.monotonic() > deadline:
                    raise AssertionError('Relay did not start')
                time.sleep(0.05)
            port = int(json.loads(status.read_text())['listen'].split(':')[1])
            original_sender = None
            for payload in (b'time=12.5\r\npitch=0.1\r\nbank=-0.2\r\n\0', bytes(range(256))):
                simulator.sendto(payload, ('127.0.0.1', port))
                actual, sender = phone.recvfrom(65535)
                assert actual == payload, 'Forwarding changed packet bytes'
                if original_sender is not None:
                    assert sender == original_sender, 'Relay changed its source socket'
                original_sender = sender
                time.sleep(1.1)
            process.terminate()
            process.communicate(timeout=5)
            state = json.loads(status.read_text())
            assert process.returncode == 0 and state['state'] == 'stopped'
            assert state['received'] == 2 and state['sent_to_os'] == 2 and state['send_errors'] == 0
        finally:
            if process.poll() is None:
                process.terminate()
                process.communicate(timeout=5)
    print('PASS: packets unchanged, stable sender, idle recovery, clean shutdown; isolated loopback only.')


def self_test_nmea_tcp():
    def sentence(body):
        checksum = 0
        for byte in body:
            checksum ^= byte
        return b'$' + body + b'*%02X' % checksum

    def fix(utc, quality=1):
        return sentence(b'GPGGA,%s,4621.5373,N,01410.2986,E,%d,12,1.0,506.2,M,,,,,0000' % (utc, quality))

    generic = b'time=12.5\r\npitch=0.1\r\nbank=-0.2\r\ncompass=145\r\naltitude=506.2\r\n'
    heading = sentence(b'LXWP0,Y,0.5,506.2,0.00,,,,,,144,180,0.0')
    nav = CondorNavigation(0)
    first_fix = fix(b'120000.288')
    sentences = first_fix + b'\r\n' + heading + b'\r\n'
    assert nav.enrich(generic, 1, 0) == generic
    nav.feed(sentences, 0.1)
    assert b'nmea_heading_offset_deg=0' in nav.enrich(generic, 1, 0.2)
    assert nav.enrich(generic, 2, 0.3) == generic
    nav.feed(sentences, 1.99)
    assert nav.enrich(generic, 2, 2.4) == generic, 'new simulator inherited previous fix'
    nav.feed(sentences, 2.5)
    assert b'nmea_heading_offset_deg=0' in nav.enrich(generic, 2, 2.6), 'new simulator could not reacquire'
    nav.feed(fix(b'120001.288', 0) + b'\r\n' + first_fix + b'\r\n', 2.7)
    assert nav.enrich(generic, 2, 2.8) == generic, 'old NMEA overrode a lost fix'
    nav.feed(fix(b'120002.288') + b'\r\n' + heading + b'\r\n', 4.5)
    assert nav.enrich(generic, 2, 4.6) == generic, 'frozen simulator accepted newer serial data'
    assert nav.enrich(generic.replace(b'12.5', b'12.51'), 2, 4.7) == generic.replace(b'12.5', b'12.51')
    with ExitStack() as stack, tempfile.TemporaryDirectory(prefix='airhorizon-nmea-test-') as directory, \
            socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as phone, \
            socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as simulator, \
            socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as other:
        phone.bind(('127.0.0.1', 0))
        phone.settimeout(2)
        status = Path(directory) / 'status.json'
        keyboard = None
        terminal = subprocess.DEVNULL
        if os.name == 'posix':
            keyboard, terminal = os.openpty()
            stack.callback(os.close, keyboard)
            stack.callback(os.close, terminal)
        process = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), '--host', '127.0.0.1',
                                    '--port', str(phone.getsockname()[1]), '--listen-port', '0',
                                    '--nmea-tcp-port', '0', '--status', str(status)], stdin=terminal)
        try:
            deadline = time.monotonic() + 15
            while not status.exists():
                if process.poll() is not None or time.monotonic() >= deadline:
                    raise AssertionError('NMEA relay did not start')
                time.sleep(0.02)
            state = json.loads(status.read_text())
            destination = ('127.0.0.1', int(state['listen'].rsplit(':', 1)[1]))
            tcp = ('127.0.0.1', state['nmea_tcp_port'])

            started = time.monotonic()
            def forward_once(source=simulator, payload=generic):
                sent = payload
                if payload == generic:
                    game_time = f'{12.5 + (time.monotonic() - started) / 3600:.8f}'.encode()
                    sent = generic.replace(b'12.5', game_time, 1)
                source.sendto(sent, destination)
                packet = phone.recvfrom(65535)[0]
                return payload + packet[len(sent):] if packet.startswith(sent) else packet

            def wait_for(matches, failure):
                deadline = time.monotonic() + 1
                while time.monotonic() < deadline:
                    result = forward_once()
                    if matches(result):
                        return result
                    time.sleep(0.02)
                raise AssertionError(failure)

            assert forward_once() == generic, 'UDP without a fix changed'
            with socket.create_connection(tcp, timeout=2) as nmea:
                first = fix(b'120000.288')
                nmea.sendall(first[:12])
                assert forward_once() == generic, 'partial NMEA sentence accepted'
                nmea.sendall(first[12:] + b'\r\n' + heading + b'\r\n')
                result = wait_for(lambda data: b'nmea_lxwp0=' + heading in data, 'fresh heading missing')
                assert b'nmea_gga=' + first in result and b'nmea_heading_offset_deg=' not in result
                if keyboard is not None:
                    os.write(keyboard, b'190\n')
                    assert b'nmea_heading_offset_deg=' not in forward_once()
                    for offset in (b'-4.5', b'0'):
                        os.write(keyboard, offset + b'\n')
                        wait_for(lambda data: b'nmea_heading_offset_deg=' + offset in data, 'live calibration failed')
                assert forward_once(other) == generic, 'foreign UDP sender received a position'
                assert forward_once(payload=b'DATA\0\xff') == b'DATA\0\xff', 'non-Condor UDP was enriched'
                time.sleep(0.15)
                fields = dict(line.split(b'=', 1) for line in forward_once().strip().splitlines())
                assert 100 <= int(fields[b'nmea_gga_age_ms']) < 2000, 'a cached fix acquired a new age'
                nmea.sendall(fix(b'120001.288', 0) + b'\r\n')
                wait_for(lambda data: data == generic, 'lost fix retained old position')
                second = fix(b'120002.288')
                nmea.sendall(second + b'\r\n')
                wait_for(lambda data: b'nmea_gga=' + second in data, 'new fix did not recover')
            wait_for(lambda data: data == generic, 'disconnected NMEA still enriched HUD')
            with socket.create_connection(tcp, timeout=2) as nmea:
                assert forward_once() == generic, 'new connection reused previous NMEA'
                third = fix(b'120003.288')
                nmea.sendall(third + b'\r\n')
                wait_for(lambda data: b'nmea_gga=' + third in data, 'reconnected stream did not recover')
                until = time.monotonic() + 2.2
                while time.monotonic() < until:
                    nmea.sendall(third + b'\r\n')
                    forward_once()
                    time.sleep(0.1)
                assert forward_once() == generic, 'duplicate GGA extended fix freshness'
        finally:
            process.terminate()
            process.wait(timeout=5)
    print('PASS: NMEA navigation, live calibration on POSIX, source takeover, invalidation, reconnect and expiry.')


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--host', type=ipaddress.IPv4Address)
    parser.add_argument('--port', type=int, default=49000)
    parser.add_argument('--listen-port', type=int, default=49000)
    parser.add_argument('--status', type=Path, default=Path('/private/tmp/AirHorizon-Condor-UDP/status.json'))
    streams = parser.add_mutually_exclusive_group()
    streams.add_argument('--nmea-pty', type=Path, metavar='NEW_LINK', help='create a PTY for Condor and link it at this unused path')
    streams.add_argument('--nmea-serial', type=Path, metavar='DEVICE', help='read NMEA from an existing serial port')
    streams.add_argument('--nmea-tcp-port', type=int, metavar='PORT', help='listen for a single NMEA client on 127.0.0.1')
    parser.add_argument('--nmea-baud', type=int, choices=(4800, 9600, 19200, 38400, 57600, 115200), default=4800)
    parser.add_argument('--heading-offset-deg', type=float, help='verified signed true runway bearing minus stationary LXWP0 nose heading')
    parser.add_argument('--self-test', action='store_true')
    args = parser.parse_args()
    if args.self_test:
        self_test()
        self_test_nmea_tcp()
        return
    if args.host is None:
        parser.error('--host must be the receiving iPhone/iPad IPv4 address')
    if not 1 <= args.port <= 65535 or not 0 <= args.listen_port <= 65535:
        parser.error('Invalid UDP port')
    if os.name != 'posix' and (args.nmea_serial is not None or args.nmea_pty is not None):
        parser.error('Serial and PTY inputs require macOS or POSIX; use --nmea-tcp-port on Windows')
    if args.nmea_tcp_port is not None and not 0 <= args.nmea_tcp_port <= 65535:
        parser.error('Invalid NMEA TCP port')
    if args.heading_offset_deg is not None:
        if not -180 <= args.heading_offset_deg <= 180:
            parser.error('--heading-offset-deg must be between -180 and 180')
        if args.nmea_pty is None and args.nmea_serial is None and args.nmea_tcp_port is None:
            parser.error('--heading-offset-deg requires an NMEA input')
    args.host = str(args.host)
    try:
        forward(args)
    except OSError as error:
        raise SystemExit(str(error)) from error


if __name__ == '__main__':
    main()
