#!/usr/bin/env python3
"""Local review server for the OKELIS portfolio.

    python3 serve.py            → http://localhost:8080/review/

Serves the portfolio folder and stands in for api.php so that comments
persist to review/comments.json exactly as they will on cPanel.
"""
import http.server, socketserver, json, os, sys, webbrowser, threading

ROOT = os.path.dirname(os.path.abspath(__file__))
STORE = os.path.join(ROOT, "review", "comments.json")
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080


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

    def _json(self, obj, code=200):
        b = json.dumps(obj).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(b)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(b)

    def do_GET(self):
        if self.path.split("?")[0].endswith("/review/api.php"):
            try:
                with open(STORE) as f:
                    return self._json(json.load(f))
            except Exception:
                return self._json([])
        return super().do_GET()

    def do_POST(self):
        if self.path.split("?")[0].endswith("/review/api.php"):
            n = int(self.headers.get("Content-Length", 0))
            try:
                data = json.loads(self.rfile.read(n) or b"[]")
                os.makedirs(os.path.dirname(STORE), exist_ok=True)
                with open(STORE, "w") as f:
                    json.dump(data, f, indent=1)
                print(f"  saved {len(data)} comment(s) → review/comments.json")
                return self._json({"ok": True, "count": len(data)})
            except Exception as e:
                return self._json({"ok": False, "error": str(e)}, 400)
        self.send_error(405)

    def log_message(self, fmt, *args):
        if "api.php" not in (args[0] if args else ""):
            super().log_message(fmt, *args)


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


if __name__ == "__main__":
    url = f"http://localhost:{PORT}/review/"
    print(f"\n  OKELIS portfolio review")
    print(f"  {url}")
    print(f"  comments → review/comments.json")
    print(f"  ctrl-c to stop\n")
    threading.Timer(0.8, lambda: webbrowser.open(url)).start()
    with Server(("", PORT), Handler) as httpd:
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n  stopped")
