"""Local test receiver: never forwards requests to Web or any other endpoint."""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from pathlib import Path
import threading
import time
import signal
import sys

LOCK=threading.Lock()
ROOT=Path('/results')

class Handler(BaseHTTPRequestHandler):
    def log_message(self,*args):pass
    def do_POST(self):
        size=int(self.headers.get('Content-Length','0'))
        if not 0<size<1048576:
            self.send_error(413);return
        data=json.loads(self.rfile.read(size))
        with LOCK:
            with (ROOT/'local-events.jsonl').open('a') as f:
                scope=self.headers.get('X-CT-Test-Scope','ISOLATED_REAL_INPUT')
                if scope not in ('ISOLATED_REAL_INPUT','OFFLINE_DELIVERY_RECHECK'):scope='UNKNOWN_TEST_SCOPE'
                f.write(json.dumps(dict(receivedAt=time.time(),scope=scope,body=data))+'\n')
        body=json.dumps({'result':True,'data':{'accepted':1,'duplicated':0}}).encode()
        self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(body)

signal.signal(signal.SIGTERM,lambda *_:sys.exit(0))
ThreadingHTTPServer(('0.0.0.0',8080),Handler).serve_forever()
