#!/usr/bin/env python3
# 简单的HTTP服务器用于端口测试

from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import socket
import time

class SimpleHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        print(f"收到请求: {self.path}")

        # 设置响应头
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()

        # 根据路径返回不同响应
        if self.path == '/':
            response = {
                "message": "简单HTTP服务器运行正常",
                "port": 8080,
                "status": "ok"
            }
        elif self.path == '/health':
            response = {
                "status": "healthy",
                "timestamp": time.time(),
                "server": "simple-http-server"
            }
        elif self.path == '/api/v1/health':
            response = {
                "status": "healthy",
                "timestamp": time.time(),
                "version": "1.0.0",
                "server": "simple-http-server"
            }
        elif self.path == '/test':
            response = {
                "test": "ok",
                "message": "测试端点正常工作"
            }
        else:
            response = {
                "error": "Not Found",
                "message": "路径不存在",
                "path": self.path
            }

        self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))

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

def check_port_available(port):
    """检查端口是否可用"""
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind(('0.0.0.0', port))
        return True
    except OSError:
        return False

def main():
    port = 8080

    print("🔍 检查端口可用性...")
    if not check_port_available(port):
        print(f"❌ 端口 {port} 被占用")
        # 尝试其他端口
        for test_port in range(8001, 8010):
            if check_port_available(test_port):
                print(f"✅ 使用端口 {test_port}")
                port = test_port
                break
        else:
            print("❌ 无法找到可用端口")
            return

    print(f"🚀 启动简单HTTP服务器在端口 {port}")
    print("=" * 50)
    print(f"📍 本地访问: http://localhost:{port}")
    print(f"📋 测试端点:")
    print(f"   根路径: http://localhost:{port}/")
    print(f"   健康检查: http://localhost:{port}/health")
    print(f"   API健康: http://localhost:{port}/api/v1/health")
    print(f"   测试端点: http://localhost:{port}/test")
    print("=" * 50)
    print("⏹️  按 Ctrl+C 停止服务")

    try:
        server = HTTPServer(('0.0.0.0', port), SimpleHandler)
        print(f"✅ 服务器已启动在端口 {port}")
        server.serve_forever()
    except KeyboardInterrupt:
        print("\n🛑 服务器已停止")
    except Exception as e:
        print(f"❌ 服务器错误: {e}")

if __name__ == "__main__":
    main()