package com.axis.innovators.box.util;

import org.python.core.Py;
import org.python.core.PyException;
import org.python.util.PythonInterpreter;
import java.util.Objects;

/**
 * 增强的Python脚本执行结果封装
 */
public final class PythonResult implements AutoCloseable {
    private final int exitCode;
    private final Object output;
    private final PythonInterpreter interpreter;

    PythonResult(int exitCode, Object output, PythonInterpreter interpreter) {
        this.exitCode = exitCode;
        this.output = output;
        this.interpreter = interpreter;
    }

    /**
     * 创建成功结果
     */
    public static PythonResult success(Object output, PythonInterpreter interpreter) {
        return new PythonResult(0, output, Objects.requireNonNull(interpreter));
    }

    /**
     * 创建错误结果
     */
    public static PythonResult error(int exitCode, String message) {
        return new PythonResult(exitCode, message, null);
    }

    public static PythonResult of(int exitCode, Object output, PythonInterpreter interpreter) {
        return new PythonResult(exitCode, output, interpreter);
    }

    public int getExitCode() {
        return exitCode;
    }

    public Object getOutput() {
        return output;
    }

    public boolean isSuccess() {
        return exitCode == 0 && interpreter != null;
    }

    /**
     * 获取解释器实例
     * @throws IllegalStateException 如果解释器不可用
     */
    public PythonInterpreter getInterpreter() {
        if (interpreter == null) {
            throw new IllegalStateException("Python interpreter not available");
        }
        return interpreter;
    }

    /**
     * 安全调用Python函数
     * @param functionName 目标函数名称
     * @param parameters 函数参数（支持基本类型和字符串）
     * @return 函数执行结果
     * @throws IllegalStateException 如果解释器不可用
     * @throws RuntimeException 如果Python执行出错
     */
    public Object callFunction(String functionName, Object... parameters) {
        PythonInterpreter pyInterp = this.getInterpreter();
        if (pyInterp == null) {
            throw new IllegalStateException("Interpreter not available");
        }

        try {
            StringBuilder args = new StringBuilder();
            for (Object param : parameters) {
                if (param instanceof String) {
                    args.append("\"").append(param.toString().replace("\"", "\\\"")).append("\",");
                } else if (param instanceof Number || param instanceof Boolean) {
                    args.append(param).append(",");
                } else {
                    args.append("\"").append(param.toString()).append("\",");
                }
            }

            if (!args.isEmpty()) {
                args.deleteCharAt(args.length() - 1);
            }

            String callExpr = functionName + "(" + args.toString() + ")";
            return pyInterp.eval(callExpr);
        } catch (PyException e) {
            throw new RuntimeException("Python error: " + e.getMessage());
        }
    }

    public boolean isValid() {
        return this.interpreter != null;
    }

    @Override
    public void close() {
        if (interpreter != null) {
            interpreter.cleanup();
            interpreter.close();
        }
    }

    @Override
    public String toString() {
        return String.format(
                "PythonResult{exitCode=%d, output=%s, interpreter=%s}",
                exitCode,
                output,
                interpreter != null ? "available" : "null"
        );
    }
}