import http.server
import socketserver
import urllib.request
import urllib.error
import urllib.parse

PORT = 3000
TARGET_HOST = 'localhost'
TARGET_PORT = 5002

class ProxyHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # 构建目标 URL
        target_url = f'http://{TARGET_HOST}:{TARGET_PORT}{self.path}'
        print(f'Proxying GET request to: {target_url}')
        
        try:
            # 转发请求到目标服务器
            req = urllib.request.Request(target_url)
            # 复制请求头
            for key, value in self.headers.items():
                if key not in ['Host', 'Connection']:
                    req.add_header(key, value)
            
            # 发送请求并获取响应
            with urllib.request.urlopen(req) as response:
                # 获取响应状态码和头
                status_code = response.getcode()
                headers = response.getheaders()
                content = response.read()
                
                # 发送响应给客户端，添加 CORS 头
                self.send_response(status_code)
                for key, value in headers:
                    # 跳过可能导致冲突的头
                    if key not in ['Content-Length', 'Transfer-Encoding', 'Connection']:
                        self.send_header(key, value)
                # 添加 CORS 头
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
                self.send_header('Access-Control-Allow-Headers', '*')
                self.end_headers()
                
                # 发送响应内容
                self.wfile.write(content)
                
        except urllib.error.HTTPError as e:
            # 处理 HTTP 错误
            self.send_response(e.code)
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(e.read())
        except Exception as e:
            # 处理其他错误
            self.send_response(500)
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(str(e).encode())

    def do_POST(self):
        # 构建目标 URL
        target_url = f'http://{TARGET_HOST}:{TARGET_PORT}{self.path}'
        print(f'Proxying POST request to: {target_url}')
        
        try:
            # 读取请求体
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            # 转发请求到目标服务器
            req = urllib.request.Request(target_url, data=post_data)
            # 复制请求头
            for key, value in self.headers.items():
                if key not in ['Host', 'Connection', 'Content-Length']:
                    req.add_header(key, value)
            
            # 发送请求并获取响应
            with urllib.request.urlopen(req) as response:
                # 获取响应状态码和头
                status_code = response.getcode()
                headers = response.getheaders()
                content = response.read()
                
                # 发送响应给客户端，添加 CORS 头
                self.send_response(status_code)
                for key, value in headers:
                    # 跳过可能导致冲突的头
                    if key not in ['Content-Length', 'Transfer-Encoding', 'Connection']:
                        self.send_header(key, value)
                # 添加 CORS 头
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
                self.send_header('Access-Control-Allow-Headers', '*')
                self.end_headers()
                
                # 发送响应内容
                self.wfile.write(content)
                
        except urllib.error.HTTPError as e:
            # 处理 HTTP 错误
            self.send_response(e.code)
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(e.read())
        except Exception as e:
            # 处理其他错误
            self.send_response(500)
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(str(e).encode())

    def do_OPTIONS(self):
        # 处理 OPTIONS 请求（预检请求）
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', '*')
        self.end_headers()

if __name__ == '__main__':
    with socketserver.TCPServer(('', PORT), ProxyHandler) as httpd:
        print(f'Proxy server running at http://localhost:{PORT}')
        print(f'Forwarding requests to http://{TARGET_HOST}:{TARGET_PORT}')
        httpd.serve_forever()
