from http.server import HTTPServer, SimpleHTTPRequestHandler
import os
import sys
import json
from pathlib import Path

# Get the directory of this script
SCRIPT_DIR = Path(__file__).parent.resolve()

class MapServerHandler(SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        # Set the directory to serve files from
        super().__init__(*args, directory=str(SCRIPT_DIR), **kwargs)
    
    def end_headers(self):
        # Add CORS headers to allow access from anywhere
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', '*')
        self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
        super().end_headers()
    
    def do_GET(self):
        # Handle map_data.json request
        if self.path == '/map_data.json':
            try:
                # Try to load from parent directory's data module
                sys.path.insert(0, str(SCRIPT_DIR.parent))
                from data.world_loader import export_map_data
                
                map_data = export_map_data()
                
                self.send_response(200)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps(map_data, indent=2).encode())
                return
            except Exception as e:
                print(f"Error generating map data: {e}")
                # Fall back to static file if it exists
                map_file = SCRIPT_DIR / 'map_data.json'
                if map_file.exists():
                    with open(map_file, 'r') as f:
                        self.send_response(200)
                        self.send_header('Content-type', 'application/json')
                        self.end_headers()
                        self.wfile.write(f.read().encode())
                        return
                
                self.send_error(500, f"Failed to generate map data: {str(e)}")
                return
        
        # Handle image requests from parent images directory
        if self.path.startswith('/images/'):
            try:
                # Construct path to image in parent directory
                image_path = SCRIPT_DIR.parent / self.path.lstrip('/')
                
                if image_path.exists() and image_path.is_file():
                    # Determine content type based on file extension
                    content_types = {
                        '.png': 'image/png',
                        '.jpg': 'image/jpeg',
                        '.jpeg': 'image/jpeg',
                        '.gif': 'image/gif',
                        '.webp': 'image/webp',
                        '.svg': 'image/svg+xml'
                    }
                    ext = image_path.suffix.lower()
                    content_type = content_types.get(ext, 'application/octet-stream')
                    
                    with open(image_path, 'rb') as f:
                        self.send_response(200)
                        self.send_header('Content-type', content_type)
                        self.end_headers()
                        self.wfile.write(f.read())
                        return
                else:
                    self.send_error(404, f"Image not found: {self.path}")
                    return
            except Exception as e:
                print(f"Error serving image {self.path}: {e}")
                self.send_error(500, f"Failed to serve image: {str(e)}")
                return
        
        # Serve other files normally
        return super().do_GET()

def run_server(port=8080):
    server_address = ('', port)
    httpd = HTTPServer(server_address, MapServerHandler)
    print(f"""
╔════════════════════════════════════════════╗
║   Echoes of the Ashes - Map Server        ║
╚════════════════════════════════════════════╝

🗺️  Map server running on:
   → http://localhost:{port}
   → http://0.0.0.0:{port}

📊 Serving from: {SCRIPT_DIR}

Press Ctrl+C to stop the server
""")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n\n👋 Shutting down server...")
        httpd.shutdown()

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='Run the RPG map visualization server')
    parser.add_argument('--port', type=int, default=8080, help='Port to run the server on (default: 8080)')
    args = parser.parse_args()
    
    run_server(args.port)
