import json
import os
import logging
from http.server import HTTPServer, SimpleHTTPRequestHandler

logging.disable(logging.CRITICAL)

with open('core.json') as f:
    config = json.load(f)

class CustomHTTPRequestHandler(SimpleHTTPRequestHandler):
    def translate_path(self, path):
        if path == '/':
            path = '/index.html'
        return os.path.join(config['DIST_PATH'], path.lstrip('/'))

    def do_GET(self):
        if self.path.startswith('/api/'):
            import sys
            sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))
            from server import handle_api_request
            handle_api_request(self)
        else:
            super().do_GET()

def run(server_class=HTTPServer, handler_class=CustomHTTPRequestHandler, port=3000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Starting httpd server on port {port}...')
    httpd.serve_forever()

if __name__ == "__main__":
    run()
