"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FridayConfigManager = void 0;
const server_1 = require("./server");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const socket_1 = require("../../../server/src/trpc/socket");
const child_process_1 = require("child_process");
class FridayConfigManager {
    constructor() {
        this.config = null;
        this.loadFridayConfig();
    }
    static getInstance() {
        if (!FridayConfigManager.instance) {
            FridayConfigManager.instance = new FridayConfigManager();
        }
        return FridayConfigManager.instance;
    }
    loadFridayConfig() {
        const fridayConfigPath = server_1.PATHS.getFridayConfigPath();
        try {
            if (fs_1.default.existsSync(fridayConfigPath)) {
                const fridayConfig = JSON.parse(fs_1.default.readFileSync(fridayConfigPath, 'utf8'));
                this.config = Object.assign(Object.assign({}, this.config), fridayConfig);
            }
        }
        catch (error) {
            console.error('Failed to load friday config:', error);
        }
    }
    getConfig() {
        return this.config;
    }
    saveConfig() {
        try {
            const fridayConfigPath = server_1.PATHS.getFridayConfigPath();
            fs_1.default.mkdirSync(path_1.default.dirname(fridayConfigPath), { recursive: true });
            fs_1.default.writeFileSync(fridayConfigPath, JSON.stringify(this.config, null, 2));
        }
        catch (error) {
            console.error('Failed to save friday config:', error);
        }
    }
    updateConfig(newConfig) {
        this.config = Object.assign(Object.assign({}, this.config), newConfig);
        this.saveConfig();
    }
    verifyPythonEnv(pythonEnv) {
        const pythonPath = path_1.default.normalize(pythonEnv);
        // Check if the file exists
        if (!fs_1.default.existsSync(pythonPath)) {
            return {
                success: false,
                message: 'The Python environment path does not exist.',
            };
        }
        // Check if the path is a file
        try {
            const stats = fs_1.default.statSync(pythonPath);
            if (!stats.isFile()) {
                return {
                    success: false,
                    message: 'Not a valid Python environment path.',
                };
            }
        }
        catch (error) {
            return {
                success: false,
                message: `Error accessing Python environment path: ${error}`,
            };
        }
        // Check if the python version is 3.10 or higher
        try {
            const cmd = process.platform === 'win32'
                ? `"${pythonPath}" --version`
                : `${pythonPath} --version`;
            const versionOutput = (0, child_process_1.execSync)(cmd, { encoding: 'utf8' })
                .toString()
                .trim();
            const versionMatch = versionOutput.match(/Python (\d+)\.(\d+)/);
            if (!versionMatch) {
                return {
                    success: false,
                    message: 'Failed to get Python version.',
                };
            }
            const major = parseInt(versionMatch[1], 10);
            const minor = parseInt(versionMatch[2], 10);
            if (major < 3 || (major === 3 && minor < 10)) {
                return {
                    success: false,
                    message: 'Python version must be 3.10 or higher.',
                };
            }
            return {
                success: true,
                message: 'Configuration is valid.',
            };
        }
        catch (_a) {
            return {
                success: false,
                message: 'Not a valid Python environment.',
            };
        }
    }
    installRequirements(pythonEnv) {
        return __awaiter(this, void 0, void 0, function* () {
            const res = yield (0, socket_1.runPythonScript)(pythonEnv, [
                '-m',
                'pip',
                'install',
                'agentscope[full]',
            ]);
            console.debug('Install requirements:', res);
            if (res.success) {
                return {
                    success: true,
                    message: 'Successfully installed requirements',
                };
            }
            else {
                return {
                    success: false,
                    message: `Failed to install requirements: ${res.error}`,
                };
            }
        });
    }
    getDefaultMainScriptPath() {
        if (process.env.NODE_ENV === 'production') {
            // In production, the structure is:
            // dist/
            //   server/
            //     src/
            //       index.js (current __dirname)
            //   app/
            //     friday/
            //       main.py
            return path_1.default.join(__dirname, '../../../app/friday/main.py');
        }
        // In development, the structure is:
        // packages/
        //   server/
        //     src/
        //       index.ts (current __dirname)
        //   app/
        //     friday/
        //       main.py
        return path_1.default.join(__dirname, '../../../app/friday/main.py');
    }
}
exports.FridayConfigManager = FridayConfigManager;
