"""Servidor local do Dashboard YouTube.
Serve os arquivos estáticos e expõe POST /atualizar, que roda o
atualizar_dashboard.py (busca os últimos dias disponíveis via API oficial)
e reescreve o dashboard_youtube.html no lugar.
Uso: python servidor_dashboard.py [porta]  (padrão 8080)
"""
import os, sys, json, subprocess, functools
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer

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


class Handler(SimpleHTTPRequestHandler):
    def _json(self, code, obj):
        body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Cache-Control", "no-store")
        super(SimpleHTTPRequestHandler, self).end_headers()
        self.wfile.write(body)

    def do_GET(self):
        # feature-detection: o dashboard mostra o botão Atualizar se /health responder
        if self.path.split("?")[0] == "/health":
            self._json(200, {"ok": True})
            return
        super().do_GET()

    def do_POST(self):
        if self.path.split("?")[0] == "/atualizar":
            try:
                r = subprocess.run(
                    [sys.executable, os.path.join(BASE, "atualizar_dashboard.py")],
                    capture_output=True, text=True, cwd=BASE, timeout=600,
                )
                ok = r.returncode == 0
                self._json(200 if ok else 500, {
                    "ok": ok,
                    "stdout": (r.stdout or "")[-3000:],
                    "stderr": (r.stderr or "")[-3000:],
                })
            except Exception as e:
                self._json(500, {"ok": False, "error": str(e)})
            return
        self._json(404, {"ok": False, "error": "rota não encontrada"})

    def end_headers(self):
        # dados sempre frescos ao recarregar o HTML após atualizar
        if self.path.endswith(".html"):
            self.send_header("Cache-Control", "no-store")
        super().end_headers()

    def log_message(self, fmt, *args):
        sys.stderr.write("%s - %s\n" % (self.address_string(), fmt % args))


if __name__ == "__main__":
    handler = functools.partial(Handler, directory=BASE)
    httpd = ThreadingHTTPServer(("0.0.0.0", PORT), handler)
    print(f"Servidor do dashboard em http://localhost:{PORT}/dashboard_youtube.html")
    print("POST /atualizar para buscar os últimos dados.")
    httpd.serve_forever()
