"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Strategy = void 0;
const tslib_1 = require("tslib");
const fs = (0, tslib_1.__importStar)(require("node:fs"));
const ajv_1 = (0, tslib_1.__importDefault)(require("ajv"));
const app_loader_1 = require("@steerprotocol/app-loader");
const form_data_1 = (0, tslib_1.__importDefault)(require("form-data"));
const axios_1 = (0, tslib_1.__importDefault)(require("axios"));
class Strategy {
    constructor(strategyPath) {
        this.module = null;
        this.results = [];
        this.configParams = {};
        this.candles = [];
        this.numCandles = 15;
        this.ipfsHash = '';
        this.filePath = strategyPath;
        this.config = {};
    }
    getEnvImports() {
        return {};
    }
    async uploadToPinata() {
        const formData = new form_data_1.default();
        formData.append('theFiles', fs.createReadStream(this.filePath));
        const ipfsHash = await axios_1.default
            .post('https://upload.steer.finance/api/upload/', formData, {
            headers: {
                ...formData.getHeaders(),
                Origin: 'http://localhost:3000',
            },
        })
            .then(({ data }) => {
            return data.data.IpfsHash;
        })
            .catch(error => {
            console.log('error uploading file and getting hash', error);
        });
        if (ipfsHash) {
            this.ipfsHash = ipfsHash;
            console.log('🚀 ~ file: Strategy.ts:46 ~ Strategy ~ uploadToPinata ~ ipfsHash:', ipfsHash);
        }
    }
    async load() {
        const module = await (0, app_loader_1.loadWasm)(this.filePath, this.getEnvImports());
        this.module = module;
        this.config = await this._getConfig();
        return module;
    }
    async execute(candles) {
        let result;
        const results = [];
        try {
            await this.load();
            if (!this.module) {
                throw new Error('Strategy not loaded');
            }
            const jsonPrices = JSON.stringify((candles || this.candles).map(val => {
                return {
                    open: Number(val.open),
                    high: Number(val.high),
                    close: Number(val.close),
                    low: Number(val.low),
                };
            }));
            // Check versioning
            // const version = this.module.version()
            this.module.initialize(JSON.stringify(this.configParams));
            try {
                result = this.module.execute(jsonPrices);
            }
            catch {
                await fs.promises.writeFile('./error.json', JSON.stringify(jsonPrices, null, 4));
                // console.error(jsonPrices)
            }
        }
        catch { }
        if (result === 'continue')
            return result;
        const parsedResult = JSON.parse(result || '{}');
        results.push(parsedResult);
        this.results = results;
        return parsedResult;
    }
    async _getConfig() {
        if (!this.module) {
            throw new Error('Strategy not loaded');
        }
        const result = this.module.config();
        return JSON.parse(result);
    }
    async getConfig() {
        if (!this.config) {
            throw new Error('Strategy not loaded, load strategy before using getConfig()');
        }
        return this.config;
    }
    setConfigParams(configParams) {
        this.configParams = configParams;
        return this.configParams;
    }
    setCandles(candles) {
        this.candles = candles;
        return this.candles;
    }
    validateParams(configParams) {
        const ajv = new ajv_1.default({ allErrors: true, strictSchema: false });
        const validate = ajv.compile(this.config);
        const valid = validate(configParams);
        return [valid, validate.errors];
    }
    getResults() {
        if (!this.results) {
            throw new Error('Strategy not executed');
        }
        return this.results;
    }
}
exports.Strategy = Strategy;
