"""Bridge local decoder JSON over authenticated HTTPS with a bounded durable spool."""
import argparse
import json
import logging
import socketserver
import sqlite3
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path
from urllib.parse import urlsplit
from uuid import UUID

LIMIT = 65536
MAX_SPOOL = 64 * 1024 * 1024
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None

class Spool:
    def __init__(self, path):
        self.db = sqlite3.connect(path, check_same_thread=False)
        self.db.execute('PRAGMA journal_mode=WAL')
        self.db.execute('PRAGMA synchronous=FULL')
        self.db.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, body BLOB NOT NULL)')
        self.db.commit()
        self.lock = threading.Lock()

    def enqueue(self, body):
        if len(body) > LIMIT:
            raise ValueError('message exceeds 64 KiB')
        if not isinstance(json.loads(body), dict):
            raise ValueError('expected decoder JSON object')
        with self.lock, self.db:
            size = self.db.execute('SELECT coalesce(sum(length(body)),0) FROM messages').fetchone()[0]
            if size + len(body) > MAX_SPOOL:
                raise ValueError('64 MiB spool full; queued messages preserved')
            self.db.execute('INSERT INTO messages(body) VALUES (?)', (body,))

    def first(self):
        with self.lock:
            return self.db.execute('SELECT id,body FROM messages ORDER BY id LIMIT 1').fetchone()

    def remove(self, ident):
        with self.lock, self.db:
            self.db.execute('DELETE FROM messages WHERE id=?', (ident,))

class TCPHandler(socketserver.StreamRequestHandler):
    def handle(self):
        self.connection.settimeout(30)
        try:
            while True:
                line = self.rfile.readline(LIMIT + 2)
                if not line:
                    return
                self.server.spool.enqueue(line.strip())
        except (ValueError, RecursionError, OSError):
            logging.warning('Local decoder connection rejected or disconnected; queued messages preserved')

class UDPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        try:
            self.server.spool.enqueue(self.request[0].strip())
        except (ValueError, RecursionError):
            logging.warning('Local datagram rejected; queued messages preserved')

class TCPServer(socketserver.ThreadingTCPServer):
    allow_reuse_address = True
    daemon_threads = True

class UDPServer(socketserver.UDPServer):
    allow_reuse_address = True
    max_packet_size = LIMIT + 1

def upload_loop(spool, url, token):
    opener = urllib.request.build_opener(NoRedirect)
    while True:
        row = spool.first()
        if row is None:
            time.sleep(.2)
            continue
        ident, body = row
        req = urllib.request.Request(url, data=body, method='POST', headers={
            'Content-Type': 'application/json', 'X-Feeder-Token': token})
        try:
            with opener.open(req, timeout=30) as response:
                if response.status != 202:
                    raise OSError('Unexpected ingestion response')
            spool.remove(ident)
        except urllib.error.HTTPError as exc:
            if exc.code in (400, 413, 422):
                logging.warning('Decoder message rejected by server (HTTP %s); removing rejected message', exc.code)
                spool.remove(ident)
            else:
                # Credentials, throttling and outages preserve the spool for recovery.
                logging.warning('Upload paused (HTTP %s); message retained', exc.code)
                time.sleep(5)
        except OSError:
            logging.warning('Upload unavailable; message retained')
            time.sleep(5)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--credentials', type=Path, required=True)
    parser.add_argument('--protocol', choices=['acars', 'vdl2', 'hfdl', 'imsl', 'irdm'], required=True)
    parser.add_argument('--port', type=int, required=True)
    parser.add_argument('--bind', default='127.0.0.1')
    parser.add_argument('--spool', type=Path, required=True)
    args = parser.parse_args()
    config = json.loads(args.credentials.read_text())
    station = str(UUID(config['station_id']))
    base = config['api_url'].rstrip('/')
    parsed = urlsplit(base)
    if parsed.scheme != 'https' or parsed.username or parsed.query or parsed.fragment:
        parser.error('The contributor API must use HTTPS without embedded credentials')
    if args.protocol not in config['protocols']:
        parser.error('This station is not registered for the selected protocol')
    args.spool.parent.mkdir(parents=True, exist_ok=True)
    spool = Spool(str(args.spool))
    url = f'{base}/v1/feeders/{station}/messages/{args.protocol}'
    threading.Thread(target=upload_loop, args=(spool, url, config['token']), daemon=True).start()
    servers = []
    for cls in (TCPServer, UDPServer):
        server = cls((args.bind, args.port), TCPHandler if cls is TCPServer else UDPHandler)
        server.spool = spool
        servers.append(server)
        threading.Thread(target=server.serve_forever, daemon=True).start()
    logging.info('Listening for local %s JSON on %s:%s (TCP/UDP)', args.protocol, args.bind, args.port)
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        for server in servers:
            server.shutdown()
