import http.server
import socketserver
import os
import sys

PORT = 8788
DIRECTORY = "public"

class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
    daemon_threads = True
    allow_reuse_address = True

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

    def translate_path(self, path):
        local_path = super().translate_path(path)
        
        # Match the worker/dev-server logic:
        # /tools/<app-id> -> public/tools/<app-id>/index.html
        if path.startswith('/tools/') and '.' not in path.split('/')[-1]:
            parts = [p for p in path.split('/') if p]
            if len(parts) == 2:
                app_id = parts[1]
                app_path = os.path.join(DIRECTORY, 'tools', app_id, 'index.html')
                if os.path.exists(app_path):
                    return os.path.abspath(app_path)
            return os.path.abspath(os.path.join(DIRECTORY, 'tools.html'))

        # If the path doesn't have an extension and is not a directory, try adding .html
        if not os.path.exists(local_path) and not path.endswith('/'):
            html_path = local_path + '.html'
            if os.path.exists(html_path):
                return html_path
                
        return local_path

if __name__ == '__main__':
    # Make sure site is freshly built
    import subprocess
    subprocess.run([sys.executable, 'build.py'])
    
    server = ThreadingHTTPServer(("", PORT), Handler)
    print(f"Serving at http://localhost:{PORT}")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()
