import { ResultErr, ResultOk } from '@polywrap/result';
import JSON5 from 'json5';
import { FUNCTION_NOT_FOUND, UNDEFINED_FUNCTION_ARGS, UNDEFINED_FUNCTION_NAME, UNPARSABLE_FUNCTION_ARGS, UNKNOWN_VARIABLE_NAME, } from './prompts.js';
import { AgentVariables } from './AgentVariables.js';
export function processFunctionAndArgs(name, args, agentFunctions, variables) {
    if (!name) {
        return ResultErr(UNDEFINED_FUNCTION_NAME);
    }
    if (name.startsWith('functions.')) {
        name = name.replace('functions.', '');
    }
    const func = agentFunctions.find(f => f.definition.name === name);
    if (!func) {
        return ResultErr(FUNCTION_NOT_FOUND(name));
    }
    if (!args) {
        return ResultErr(UNDEFINED_FUNCTION_ARGS(name));
    }
    try {
        const parsedArgs = args ? JSON5.parse(args) : undefined;
        if (typeof parsedArgs === 'object') {
            for (const [key, value] of Object.entries(parsedArgs)) {
                if (typeof value === 'string' && AgentVariables.hasSyntax(value)) {
                    parsedArgs[key] = variables.get(value);
                    if (parsedArgs[key] === undefined) {
                        return ResultErr(UNKNOWN_VARIABLE_NAME(value));
                    }
                }
            }
        }
        return ResultOk([parsedArgs, func]);
    }
    catch (err) {
        return ResultErr(UNPARSABLE_FUNCTION_ARGS(name, args, err));
    }
}
export const executeAgentFunction = async ([params, func], rawParams, context) => {
    const executor = func.buildExecutor(context);
    return {
        result: await executor(params, rawParams),
        functionCalled: {
            name: func.definition.name,
            params: rawParams,
        },
    };
};
