#!/usr/bin/env python3
"""
Simple development server for the frontend that reads configuration from .env
"""

import os
import http.server
import socketserver
from pathlib import Path

# Try to load environment variables, but don't fail if dotenv is not available
try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    print("python-dotenv not installed, using system environment variables only")

# Configuration
PORT = int(os.getenv('VITE_DEV_SERVER_PORT', '8001'))
HOST = os.getenv('VITE_DEV_SERVER_HOST', '127.0.0.1')

# Change to frontend directory
frontend_dir = Path(__file__).parent
os.chdir(frontend_dir)

class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        # Add CORS headers for development
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', '*')
        super().end_headers()

if __name__ == "__main__":
    print(f"Starting Frontend Development Server...")
    print(f"Host: {HOST}")
    print(f"Port: {PORT}")
    print(f"Serving from: {frontend_dir}")
    print(f"Open: http://{HOST}:{PORT}")
    
    with socketserver.TCPServer((HOST, PORT), MyHTTPRequestHandler) as httpd:
        print(f"Server running at http://{HOST}:{PORT}/")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nShutting down server...")
