#!/usr/bin/env python3
"""
Simple HTTP server for P2P Liquidity Dashboard
"""

import http.server
import socketserver
import os
import webbrowser
import json
import urllib.parse
from pathlib import Path
from admin_api import handle_api_request

class DashboardHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(Path(__file__).parent), **kwargs)
    
    def end_headers(self):
        # Add CORS headers for local 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', 'Content-Type')
        # Prevent caching for JSON files
        if self.path.endswith('.json'):
            self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Expires', '0')
        super().end_headers()
    
    def do_GET(self):
        """Handle GET requests"""
        parsed_path = urllib.parse.urlparse(self.path)
        
        # Handle API requests
        if parsed_path.path.startswith('/api/'):
            self._handle_api_request('GET', parsed_path.path)
        else:
            # Handle static files
            super().do_GET()
    
    def do_POST(self):
        """Handle POST requests"""
        parsed_path = urllib.parse.urlparse(self.path)
        
        # Handle API requests
        if parsed_path.path.startswith('/api/'):
            self._handle_api_request('POST', parsed_path.path)
        else:
            self.send_error(405, "Method Not Allowed")
    
    def do_OPTIONS(self):
        """Handle OPTIONS requests for CORS"""
        self.send_response(200)
        self.end_headers()
    
    def _handle_api_request(self, method, path):
        """Handle API requests"""
        try:
            # Parse request data for POST requests
            data = None
            if method == 'POST':
                content_length = int(self.headers.get('Content-Length', 0))
                if content_length > 0:
                    post_data = self.rfile.read(content_length)
                    try:
                        data = json.loads(post_data.decode('utf-8'))
                    except json.JSONDecodeError:
                        self.send_error(400, "Invalid JSON")
                        return
            
            # Handle the API request
            response = handle_api_request(method, path, data)
            
            # Send response
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
            
        except Exception as e:
            # Send error response
            error_response = {
                "success": False,
                "message": f"Ошибка сервера: {str(e)}",
                "error": "Internal Server Error"
            }
            
            self.send_response(500)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(error_response, ensure_ascii=False).encode('utf-8'))

def start_dashboard_server(port=8080):
    """Start the dashboard server"""
    
    # Change to the project directory
    os.chdir(Path(__file__).parent)
    
    try:
        with socketserver.TCPServer(("", port), DashboardHandler) as httpd:
            print(f"P2P Liquidity Dashboard Server")
            print(f"Serving at: http://localhost:{port}")
            print(f"Dashboard: http://localhost:{port}/dashboard.html")
            print(f"Press Ctrl+C to stop the server")
            print("-" * 50)
            
            # Try to open browser automatically
            try:
                webbrowser.open(f'http://localhost:{port}/dashboard.html')
                print("Opening dashboard in browser...")
            except:
                print("Could not open browser automatically")
            
            httpd.serve_forever()
            
    except KeyboardInterrupt:
        print("\nServer stopped")
    except OSError as e:
        if e.errno == 48:  # Address already in use
            print(f"Port {port} is already in use. Try a different port:")
            print(f"python dashboard_server.py --port 8081")
        else:
            print(f"Error starting server: {e}")

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description='P2P Liquidity Dashboard Server')
    parser.add_argument('--port', type=int, default=8080, help='Port to serve on (default: 8080)')
    
    args = parser.parse_args()
    start_dashboard_server(args.port)
