'use server';
import { execFile } from 'node:child_process';
import { IS_WINDOWS } from '../../../../../packages/core/src/infrastructure/platform.js';
import { resolve } from '../../lib/server-container.js';
function getVersion(command, args) {
    return new Promise((resolve) => {
        try {
            const opts = IS_WINDOWS ? { timeout: 5000, windowsHide: true } : { timeout: 5000 };
            execFile(command, args, opts, (error, stdout) => {
                if (error) {
                    resolve({ installed: false, version: null });
                    return;
                }
                // Extract version number from output like "git version 2.43.0" or "gh version 2.40.1"
                const match = stdout.match(/(\d+\.\d+(?:\.\d+)?)/);
                resolve({ installed: true, version: match?.[1] ?? null });
            });
        }
        catch {
            resolve({ installed: false, version: null });
        }
    });
}
export async function checkToolStatus() {
    // Run version checks and tool metadata lookup in parallel
    const [gitVersion, ghVersion, tools] = await Promise.all([
        getVersion('git', ['--version']),
        getVersion('gh', ['--version']),
        (async () => {
            try {
                const useCase = resolve('ListToolsUseCase');
                return await useCase.execute();
            }
            catch {
                return [];
            }
        })(),
    ]);
    const gitTool = tools.find((t) => t.id === 'git');
    const ghTool = tools.find((t) => t.id === 'gh');
    return {
        git: {
            ...gitVersion,
            installCommand: gitTool?.installCommand ?? null,
            installUrl: gitTool?.website ?? 'https://git-scm.com',
        },
        gh: {
            ...ghVersion,
            installCommand: ghTool?.installCommand ?? null,
            installUrl: ghTool?.website ?? 'https://cli.github.com',
        },
    };
}
