#!/usr/bin/env python3
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import os


ROOT = Path(__file__).resolve().parents[1] / "shine-UI"
PORT = int(os.environ.get("SHINE_UI_PORT", "8088"))


class SpaHandler(SimpleHTTPRequestHandler):
    def translate_path(self, path):
        translated = super().translate_path(path)
        rel = Path(translated).relative_to(Path.cwd())
        return str(ROOT / rel)

    def do_GET(self):
        file_path = Path(self.translate_path(self.path.split("?", 1)[0]))
        if file_path.exists() and file_path.is_file():
            return super().do_GET()
        self.path = "/index.html"
        return super().do_GET()


def main():
    os.chdir(ROOT)
    server = ThreadingHTTPServer(("0.0.0.0", PORT), SpaHandler)
    print(f"SHiNE SPA server: http://localhost:{PORT}")
    server.serve_forever()


if __name__ == "__main__":
    main()
