#!/usr/bin/env python3
"""
Simple static file server for DFY website packages
Serves /sites directory on port 8082
"""
import http.server
import socketserver
import os

PORT = 8082
DIRECTORY = "/sites"

class Handler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # Construct the full path to check if it's a directory
        full_path = self.translate_path(self.path)

        if os.path.isdir(full_path):
            # If it's a directory, append index.html to the path
            self.path = os.path.join(self.path, 'index.html')
        
        return http.server.SimpleHTTPRequestHandler.do_GET(self)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)
    
    def end_headers(self):
        # Add CORS headers if needed
        self.send_header('Access-Control-Allow-Origin', '*')
        super().end_headers()


    def do_GET(self):
        # Store original path
        original_path = self.path

        # If path is a directory, try to append index.html
        if os.path.isdir(self.translate_path(original_path)):
            if not original_path.endswith('/'):
                # Redirect to add trailing slash if it's a directory without one
                self.send_response(301)
                self.send_header('Location', original_path + '/')
                self.end_headers()
                return
            self.path = os.path.join(original_path, 'index.html')

        # If after modification, the path still doesn't exist, revert and try original
        # This handles cases like /favicon.ico where it's not a directory
        if not os.path.exists(self.translate_path(self.path)) and self.path != original_path:
            self.path = original_path

        return http.server.SimpleHTTPRequestHandler.do_GET(self)
        # Override to serve index.html for directories
        if self.path.endswith('/'):
            path = self.path + 'index.html'
        else:
            path = self.path
        
        # Check if the requested path (or path + index.html) exists
        full_path = os.path.join(self.directory, path.lstrip('/'))
        if os.path.isdir(full_path):
            # If it's a directory, append index.html
            self.path = os.path.join(self.path, 'index.html')
        
        return http.server.SimpleHTTPRequestHandler.do_GET(self)
    def end_headers(self):
        # Add CORS headers if needed
        self.send_header('Access-Control-Allow-Origin', '*')
        super().end_headers()

os.chdir(DIRECTORY)

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print(f"Serving {DIRECTORY} on port {PORT}")
    httpd.serve_forever()
