"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 __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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClaudeCodePluginClient = void 0;
/**
 * Claude Code Plugin — DEPRECATED. Uninstall-only. Drop in next release.
 *
 * Previous wizard versions installed an Amplitude Claude Code plugin (slash
 * commands + bundled MCP) via `claude plugin install`. This client keeps the
 * uninstall path alive so users who have the plugin installed can remove it
 * via the wizard. The install path is intentionally a no-op — the wizard now
 * only installs the bare MCP entry through `ClaudeCodeMCPClient`.
 *
 * Detection strategy: only report `isClientSupported()` true if the plugin
 * is currently installed (probed via `claude plugin list`). That keeps it
 * out of the install picker entirely while letting it surface in the
 * uninstall flow exclusively for affected users.
 */
// `claude` ships as `claude.cmd` on Windows when installed via npm —
// stock `spawn`/`spawnSync` do not consult PATHEXT and ENOENT on the
// bare name. Route through the cross-platform wrapper.
const cross_platform_spawn_js_1 = require("../../../utils/cross-platform-spawn.js");
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const MCPClient_1 = require("../MCPClient");
const analytics_1 = require("../../../utils/analytics");
const debug_1 = require("../../../utils/debug");
const constants_1 = require("../../../lib/constants");
const PLUGIN_REF = `${constants_1.CLAUDE_PLUGIN_ID}@${constants_1.CLAUDE_PLUGIN_MARKETPLACE_NAME}`;
function findClaudeBinary() {
    const possiblePaths = [
        path.join(os.homedir(), '.local', 'bin', 'claude'),
        path.join(os.homedir(), '.claude', 'local', 'claude'),
        '/usr/local/bin/claude',
        '/opt/homebrew/bin/claude',
    ];
    for (const p of possiblePaths) {
        if (fs.existsSync(p))
            return p;
    }
    const pathDirs = (process.env.PATH ?? '').split(path.delimiter);
    for (const dir of pathDirs) {
        if (!dir)
            continue;
        const candidate = path.join(dir, 'claude');
        if (fs.existsSync(candidate))
            return candidate;
    }
    return null;
}
/** Async wrapper around spawn that captures stdout/stderr. */
function runCli(binary, args) {
    return new Promise((resolve) => {
        const proc = (0, cross_platform_spawn_js_1.spawn)(binary, args, { stdio: 'pipe' });
        const stdoutChunks = [];
        const stderrChunks = [];
        proc.stdout?.on('data', (d) => stdoutChunks.push(d));
        proc.stderr?.on('data', (d) => stderrChunks.push(d));
        proc.on('error', (err) => {
            resolve({
                status: -1,
                stdout: Buffer.concat(stdoutChunks),
                stderr: Buffer.from(err.message),
            });
        });
        proc.on('close', (status) => {
            resolve({
                status: status ?? 0,
                stdout: Buffer.concat(stdoutChunks),
                stderr: Buffer.concat(stderrChunks),
            });
        });
    });
}
class ClaudeCodePluginClient extends MCPClient_1.MCPClient {
    name = 'Claude Code Plugin';
    getServerPropertyName() {
        return 'mcpServers';
    }
    getConfigPath() {
        throw new Error('Not implemented');
    }
    /**
     * Uninstall-only: report supported only when the plugin is actually
     * installed. Keeps it out of the install picker (which uses
     * getSupportedClients) and lets it surface in getInstalledClients() for
     * the uninstall flow.
     */
    async isClientSupported() {
        return this.isServerInstalled();
    }
    async isServerInstalled() {
        const binary = findClaudeBinary();
        if (!binary)
            return false;
        try {
            // Guard against older Claude Code versions without `plugin` subcommand.
            const help = (0, cross_platform_spawn_js_1.spawnSync)(binary, ['plugin', '--help'], { stdio: 'pipe' });
            if (help.status !== 0)
                return false;
            const result = await runCli(binary, ['plugin', 'list']);
            if (result.status !== 0)
                return false;
            return result.stdout.toString().includes(PLUGIN_REF);
        }
        catch {
            return false;
        }
    }
    /** Install path retired — wizard now installs only the bare MCP entry. */
    addServer() {
        return Promise.resolve({ success: false });
    }
    async removeServer() {
        const binary = findClaudeBinary();
        if (!binary)
            return { success: false };
        const result = await runCli(binary, [
            'plugin',
            'uninstall',
            PLUGIN_REF,
            '--scope',
            'user',
        ]);
        if (result.status !== 0) {
            const err = result.stderr.toString().trim() || result.stdout.toString().trim();
            (0, debug_1.debug)(`  Failed to uninstall Amplitude plugin: ${err}`);
            analytics_1.analytics.captureException(new Error(`Failed to uninstall Amplitude plugin: ${err}`));
            return { success: false };
        }
        return { success: true };
    }
}
exports.ClaudeCodePluginClient = ClaudeCodePluginClient;
