
# Python HTTP服务包装器

import os
import sys
import json
import time
from http.server import HTTPServer, BaseHTTPRequestHandler

# 添加项目路径到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# 尝试导入算法模块
try:
    # 根据入口点导入算法
    if "{{entry_point}}" == "":
        # 尝试导入主要模块
        import algorithm
        algorithm_module = algorithm
    else:
        # 动态导入入口点
        import importlib.util
        spec = importlib.util.spec_from_file_location("algorithm_module", "{{entry_point}}")
        algorithm_module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(algorithm_module)
    print("算法模块导入成功")
except Exception as e:
    print(f"算法模块导入失败: {e}")
    algorithm_module = None

# 服务配置
HOST = os.environ.get("HOST", "{{host}}")
PORT = int(os.environ.get("PORT", "{{port}}"))
TIMEOUT = int(os.environ.get("TIMEOUT", "{{timeout}}"))

class AlgorithmRequestHandler(BaseHTTPRequestHandler):
    """算法请求处理器"""
    
    def do_POST(self):
        """处理POST请求"""
        try:
            # 读取请求体
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            # 解析请求数据
            request_data = json.loads(post_data.decode('utf-8'))
            
            # 记录请求开始时间
            start_time = time.time()
            
            # 调用算法
            result = self._call_algorithm(request_data)
            
            # 计算响应时间
            response_time = time.time() - start_time
            
            # 构建响应
            response = {
                "success": True,
                "result": result,
                "response_time": round(response_time, 4),
                "message": "算法执行成功"
            }
            
            # 发送响应
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode('utf-8'))
            
        except Exception as e:
            # 构建错误响应
            error_response = {
                "success": False,
                "error": str(e),
                "message": "算法执行失败"
            }
            
            # 发送错误响应
            self.send_response(400)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(error_response).encode('utf-8'))
    
    def do_GET(self):
        """处理GET请求"""
        if self.path == "{{health_check_path}}":
            # 健康检查
            self._handle_health_check()
        elif self.path == "/info":
            # 服务信息
            self._handle_info()
        else:
            # 404响应
            self.send_response(404)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"error": "Not Found"}).encode('utf-8'))
    
    def _call_algorithm(self, request_data):
        """调用算法
        
        Args:
            request_data: 请求数据
            
        Returns:
            算法执行结果
        """
        if algorithm_module is None:
            raise Exception("算法模块未加载")
        
        # 尝试调用算法的主要函数
        try:
            # 检查是否有predict函数
            if hasattr(algorithm_module, 'predict'):
                return algorithm_module.predict(request_data)
            # 检查是否有run函数
            elif hasattr(algorithm_module, 'run'):
                return algorithm_module.run(request_data)
            # 检查是否有main函数
            elif hasattr(algorithm_module, 'main'):
                return algorithm_module.main(request_data)
            else:
                raise Exception("未找到算法执行函数")
        except Exception as e:
            raise Exception(f"算法执行失败: {e}")
    
    def _handle_health_check(self):
        """处理健康检查"""
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps({"status": "healthy", "service": "{{project_name}}"}).encode('utf-8'))
    
    def _handle_info(self):
        """处理服务信息请求"""
        info = {
            "service": "{{project_name}}",
            "version": "1.0.0",
            "host": HOST,
            "port": PORT,
            "timeout": TIMEOUT,
            "algorithm_loaded": algorithm_module is not None
        }
        
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(info).encode('utf-8'))

def run_server():
    """启动服务"""
    server = HTTPServer((HOST, PORT), AlgorithmRequestHandler)
    print(f"服务启动成功，监听地址: {HOST}:{PORT}")
    print(f"健康检查地址: http://{HOST}:{PORT}{{health_check_path}}")
    print(f"服务信息地址: http://{HOST}:{PORT}/info")
    
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("服务停止")
        server.shutdown()

if __name__ == "__main__":
    run_server()
