"""Tiny HTTP receiver: POST <body> to /<path>, file gets written to data/raw/domrf/<path>.

Usage:
    python data/sql/upload_server.py    # listens on 127.0.0.1:8765

In browser DevTools:
    fetch('http://127.0.0.1:8765/regions.json', { method: 'POST', body: JSON.stringify(window.__domrf['regions']) });
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import sys

ROOT = os.path.join(os.path.dirname(__file__), '..', 'raw', 'domrf')
os.makedirs(ROOT, exist_ok=True)


class H(BaseHTTPRequestHandler):
    def _cors(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')

    def do_OPTIONS(self):
        self.send_response(204)
        self._cors()
        self.end_headers()

    def do_POST(self):
        try:
            length = int(self.headers.get('Content-Length', 0))
            body = self.rfile.read(length)
            name = self.path.lstrip('/').replace('..', '_').replace('\\', '_')
            if not name:
                name = 'upload.json'
            path = os.path.join(ROOT, name)
            with open(path, 'wb') as f:
                f.write(body)
            print(f'WROTE {path} ({len(body)} bytes)', flush=True)
            self.send_response(200)
            self._cors()
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(b'{"ok":true}')
        except Exception as e:
            self.send_response(500)
            self._cors()
            self.end_headers()
            self.wfile.write(str(e).encode())

    def log_message(self, *args):
        pass


if __name__ == '__main__':
    addr = ('127.0.0.1', 8765)
    print(f'listening on http://{addr[0]}:{addr[1]}, output dir: {os.path.abspath(ROOT)}', flush=True)
    HTTPServer(addr, H).serve_forever()
