#!/usr/bin/env python3
"""Local review server for richting-v9.html. Serves this folder on 127.0.0.1:8765 and appends review decisions to
review-decisions.jsonl (one JSON per line). Run: python3 review-server.py   Stop: Ctrl-C. Local only, no network."""
import http.server, json, os, time
D=os.path.dirname(os.path.abspath(__file__)); F=os.path.join(D,'review-decisions.jsonl')
def latest():
    out={}
    if os.path.exists(F):
        for l in open(F,encoding='utf-8'):
            try: d=json.loads(l)
            except Exception: continue
            out[d['key']]=d
    return out
class H(http.server.SimpleHTTPRequestHandler):
    def __init__(s,*a,**k): super().__init__(*a,directory=D,**k)
    def do_GET(s):
        if s.path.startswith('/decisions'):
            b=json.dumps(list(latest().values())).encode(); s.send_response(200); s.send_header('Content-Type','application/json'); s.send_header('Content-Length',str(len(b))); s.end_headers(); s.wfile.write(b); return
        super().do_GET()
    def end_headers(s):
        s.send_header('Cache-Control','no-store, max-age=0'); super().end_headers()
    def do_POST(s):
        if s.path!='/decide': s.send_error(404); return
        d=json.loads(s.rfile.read(int(s.headers.get('Content-Length',0))) or b'{}'); d['at']=time.strftime('%Y-%m-%d %H:%M:%S')
        open(F,'a',encoding='utf-8').write(json.dumps(d,ensure_ascii=False)+'\n'); s.send_response(204); s.end_headers()
    def log_message(s,*a): pass
if __name__=='__main__':
    import sys,threading
    hosts=sys.argv[1:] or ['127.0.0.1']   # e.g. python3 review-server.py 127.0.0.1 100.68.167.80  (tailnet only, never 0.0.0.0)
    for h in hosts:
        print('Review on http://%s:8765/richting-v9.html  (decisions -> review-decisions.jsonl)'%h)
    ss=[http.server.ThreadingHTTPServer((h,8765),H) for h in hosts]
    for x in ss[1:]: threading.Thread(target=x.serve_forever,daemon=True).start()
    ss[0].serve_forever()
