#!/usr/bin/env python3
import json, logging
from pathlib import Path
from http.server import HTTPServer, SimpleHTTPRequestHandler

BASE_DIR  = Path(__file__).parent
SUBS_FILE = BASE_DIR / "subscriptions.json"
PORT      = 8080

log = logging.getLogger("navmon-server")
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")

def load_subs():
    if SUBS_FILE.exists():
        try: return json.loads(SUBS_FILE.read_text())
        except: pass
    return []

def save_subs(subs):
    SUBS_FILE.write_text(json.dumps(subs, indent=2))

class NavMonHandler(SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(BASE_DIR), **kwargs)
    def log_message(self, fmt, *args): pass
    def send_cors(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
    def do_OPTIONS(self):
        self.send_response(204)
        self.send_cors()
        self.end_headers()
    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(length)
        if self.path == "/subscribe":
            try:
                sub = json.loads(body)
                subs = load_subs()
                if sub.get("endpoint") not in {s.get("endpoint") for s in subs}:
                    subs.append(sub)
                    save_subs(subs)
                self._json(200, {"ok": True, "count": len(subs)})
            except Exception as e:
                self._json(400, {"ok": False, "error": str(e)})
        elif self.path == "/unsubscribe":
            try:
                data = json.loads(body)
                subs = [s for s in load_subs() if s.get("endpoint") != data.get("endpoint")]
                save_subs(subs)
                self._json(200, {"ok": True, "count": len(subs)})
            except Exception as e:
                self._json(400, {"ok": False, "error": str(e)})
        else:
            self._json(404, {"ok": False})
    def do_GET(self):
        if self.path == "/api/stats":
            subs = load_subs()
            cache = {}
            history = []
            try: cache = json.loads((BASE_DIR/"cache.json").read_text())
            except: pass
            try: history = json.loads((BASE_DIR/"history.json").read_text())
            except: pass
            self._json(200, {"subscribers": len(subs), "history_count": len(history), "sources": {k: v.get("last_check") for k,v in cache.items()}})
        else:
            super().do_GET()
    def _json(self, code, data):
        body = json.dumps(data, ensure_ascii=False).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.send_cors()
        self.end_headers()
        self.wfile.write(body)

if __name__ == "__main__":
    server = HTTPServer(("0.0.0.0", PORT), NavMonHandler)
    log.info(f"NavMon Server port {PORT}")
    server.serve_forever()
