#!/usr/bin/env python3
"""this-or-that server: serves the kit dir + appends POST /vote JSON bodies to votes.jsonl."""
import json, os, sys, time
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler

ROOT = os.path.dirname(os.path.abspath(__file__))
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8477

class Handler(SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=ROOT, **kw)

    def do_POST(self):
        if self.path != "/vote":
            self.send_response(404); self.end_headers(); return
        n = int(self.headers.get("Content-Length", 0))
        try:
            data = json.loads(self.rfile.read(n) or b"{}")
        except Exception:
            data = {"error": "unparseable"}
        data["ts"] = time.strftime("%Y-%m-%dT%H:%M:%S")
        with open(os.path.join(ROOT, "votes.jsonl"), "a", encoding="utf-8") as f:
            f.write(json.dumps(data) + "\n")
        self.send_response(204); self.end_headers()

    def log_message(self, *a):
        pass

if __name__ == "__main__":
    print(f"this-or-that → http://127.0.0.1:{PORT}/compare.html")
    ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
