#!/usr/bin/env python3
import http.server
import socketserver
import sys
import os
import signal

ADDRESS = '0.0.0.0'
PORT = 8080

# Check if directory was specified as command-line argument
if len(sys.argv) > 1:
    os.chdir(sys.argv[1])
    print(f"Serving directory: {sys.argv[1]}")

Handler = http.server.SimpleHTTPRequestHandler

# Set MIME types - using text/yaml for YAML files
Handler.extensions_map = {
    '.yaml': 'application/json',
    '.yml': 'application/json',
    '.json': 'application/json',
    '': 'application/json', # octet-stream
}

# Enable socket reuse to avoid "address already in use" errors
socketserver.TCPServer.allow_reuse_address = True

# Create server
httpd = socketserver.TCPServer((ADDRESS, PORT), Handler)

print(f"Serving at http://localhost:{PORT}")
print("Press Ctrl+C to stop the server")

try:
    httpd.serve_forever()
except KeyboardInterrupt:
    print("\nShutting down server...")
    httpd.server_close()
    print("Server stopped")
