"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var McpCommand_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.McpCommand = void 0;
const nest_commander_1 = require("nest-commander");
const common_1 = require("@nestjs/common");
const child_process_1 = require("child_process");
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const solid_registry_1 = require("../helpers/solid-registry");
const create_model_metadata_dto_1 = require("../dtos/create-model-metadata.dto");
let McpCommand = McpCommand_1 = class McpCommand extends nest_commander_1.CommandRunner {
    constructor(solidRegistry) {
        super();
        this.solidRegistry = solidRegistry;
        this.logger = new common_1.Logger(McpCommand_1.name);
    }
    async run(passedParams, options) {
        const mode = (passedParams[0] || 'start').toLowerCase();
        if (mode === 'stop') {
            await this.stopContainers(options);
        }
        else if (mode === 'start') {
            await this.startContainers(options);
        }
        else {
            this.logger.error(`Unknown mode "${mode}". Supported modes are: start, stop.\n` +
                'Examples:\n' +
                '  solid mcp start -p ~/mcp/servers/solidx_mcp_server\n' +
                '  solid mcp stop  -p ~/mcp/servers/solidx_mcp_server\n');
        }
    }
    async startContainers(options) {
        const apiKey = process.env.MCP_API_KEY;
        const defaultDatabaseUser = process.env.DEFAULT_DATABASE_USER;
        const defaultDatabasePwd = process.env.DEFAULT_DATABASE_PASSWORD
            ? encodeURIComponent(process.env.DEFAULT_DATABASE_PASSWORD)
            : '';
        const defaultDatabaseHost = process.env.DEFAULT_DATABASE_HOST === 'localhost' ? 'host.docker.internal' : process.env.DEFAULT_DATABASE_HOST;
        const defaultDatabaseName = process.env.DEFAULT_DATABASE_NAME;
        const databaseDialect = process.env.DEFAULT_DATABASE_TYPE?.toLowerCase() === 'mssql' ? 'mssql+pyodbc' : 'postgresql';
        const defaultDatasource = this.solidRegistry.getDefaultSolidDatabaseModule();
        let databaseUrl;
        if (defaultDatasource.type() === create_model_metadata_dto_1.DatasourceType.mssql) {
            const base = `mssql+pyodbc://${defaultDatabaseUser}:${defaultDatabasePwd}@${defaultDatabaseHost}/${defaultDatabaseName}`;
            const driver = encodeURIComponent('ODBC Driver 18 for SQL Server');
            databaseUrl = `${base}?driver=${driver}&TrustServerCertificate=yes`;
        }
        if (defaultDatasource.type() === create_model_metadata_dto_1.DatasourceType.postgres) {
            databaseUrl = `postgresql://${defaultDatabaseUser}:${defaultDatabasePwd}@${defaultDatabaseHost}/${defaultDatabaseName}`;
        }
        if (!apiKey || apiKey.trim() === '') {
            this.logger.error('❌ MCP_API_KEY environment variable is missing.\n' +
                'Set it before running:\n' +
                '   export MCP_API_KEY="your_license_key"\n');
            return;
        }
        this.logger.log('✔ MCP_API_KEY found.');
        const repoPath = options?.repoPath ? this.resolvePath(options.repoPath) : process.cwd();
        const consumingProjectPath = path.resolve(process.cwd(), '..');
        const composeFile = path.join(repoPath, 'docker-compose.yml');
        if (!fs.existsSync(composeFile)) {
            this.logger.error(`docker-compose.yml not found at ${composeFile}`);
            return;
        }
        const detached = options?.detached ?? false;
        this.logger.log(`Mode: start`);
        this.logger.log(`Using repo path: ${repoPath}`);
        this.logger.log(`Detached mode: ${detached}`);
        this.logger.log(`Consuming project root: ${consumingProjectPath}`);
        const cmd = 'docker';
        const args = ['compose', '-f', composeFile, 'up'];
        if (detached) {
            args.push('-d');
        }
        args.push('mcp_redis', 'mcp_server', 'mcp_celery_worker');
        const env = {
            ...process.env,
            MCP_API_KEY: apiKey,
            HOST_SOLIDX_CONSUMING_PROJECT_ROOT: consumingProjectPath,
            DATABASE_URL: databaseUrl,
        };
        this.logger.log(`Running: ${cmd} ${args.join(' ')}`);
        await this.runDockerCommand(cmd, args, repoPath, env);
        this.logger.log(detached
            ? 'MCP containers started in detached mode.'
            : 'MCP containers started in foreground.');
    }
    async stopContainers(options) {
        const repoPath = options?.repoPath ? this.resolvePath(options.repoPath) : process.cwd();
        const composeFile = path.join(repoPath, 'docker-compose.yml');
        if (!fs.existsSync(composeFile)) {
            this.logger.error(`docker-compose.yml not found at ${composeFile}`);
            return;
        }
        this.logger.log(`Mode: stop`);
        this.logger.log(`Using repo path: ${repoPath}`);
        const cmd = 'docker';
        const args = ['compose', '-f', composeFile, 'down'];
        this.logger.log(`Running: ${cmd} ${args.join(' ')}`);
        await this.runDockerCommand(cmd, args, repoPath, process.env);
        this.logger.log('MCP containers stopped (docker compose down).');
    }
    resolvePath(inputPath) {
        if (inputPath.startsWith('~')) {
            return path.join(process.env.HOME, inputPath.slice(1));
        }
        return path.resolve(inputPath);
    }
    runDockerCommand(cmd, args, cwd, env) {
        return new Promise((resolve, reject) => {
            const child = (0, child_process_1.spawn)(cmd, args, {
                cwd,
                env,
                stdio: 'inherit',
            });
            child.on('error', (err) => {
                this.logger.error(`Docker error: ${err.message}`);
                reject(err);
            });
            child.on('close', (code) => {
                if (code === 0)
                    resolve();
                else
                    reject(new Error(`Docker exited with code ${code}`));
            });
        });
    }
    parseDetached(val) {
        if (val === undefined)
            return false;
        return val === 'true' || val === '1';
    }
    parseRepoPath(val) {
        return val;
    }
};
exports.McpCommand = McpCommand;
__decorate([
    (0, nest_commander_1.Option)({ flags: '-d, --detached [boolean]', description: 'Run containers in detached mode (only for start, default: false)', required: false, }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Boolean)
], McpCommand.prototype, "parseDetached", null);
__decorate([
    (0, nest_commander_1.Option)({ flags: '-p, --repo-path [path]', description: 'Path to the SolidX MCP Server repo containing docker-compose.yml', required: false, }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", String)
], McpCommand.prototype, "parseRepoPath", null);
exports.McpCommand = McpCommand = McpCommand_1 = __decorate([
    (0, nest_commander_1.Command)({
        name: 'mcp',
        description: 'Manage the SolidX MCP server and Celery worker docker containers (start/stop)',
    }),
    __metadata("design:paramtypes", [solid_registry_1.SolidRegistry])
], McpCommand);
//# sourceMappingURL=mcp.command.js.map