"use strict";
/**
 * Droid CLI Detector
 *
 * Detects Factory Droid CLI binary in PATH.
 * Mirrors claude-detector.ts pattern.
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkDroidVersion = exports.getDroidBinaryInfo = exports.detectDroidCli = void 0;
const fs = __importStar(require("fs"));
const child_process_1 = require("child_process");
const helpers_1 = require("../utils/helpers");
/**
 * Detect Droid CLI executable.
 *
 * Priority:
 * 1. CCS_DROID_PATH env var (user override)
 * 2. PATH lookup via which/where.exe
 */
function detectDroidCli() {
    // Priority 1: CCS_DROID_PATH environment variable
    if (process.env.CCS_DROID_PATH) {
        const customPath = (0, helpers_1.expandPath)(process.env.CCS_DROID_PATH);
        try {
            if (fs.statSync(customPath).isFile()) {
                return customPath;
            }
            console.warn('[!] CCS_DROID_PATH points to a directory, not a file:', customPath);
            console.warn('    Refusing PATH fallback while CCS_DROID_PATH is explicitly set.');
            return null;
        }
        catch (err) {
            const error = err;
            if (error.code === 'ENOENT') {
                console.warn('[!] Warning: CCS_DROID_PATH is set but file not found:', customPath);
            }
            else {
                console.warn(`[!] Warning: CCS_DROID_PATH is not accessible (${error.code || 'unknown error'}):`, customPath);
            }
            console.warn('    Refusing PATH fallback while CCS_DROID_PATH is explicitly set.');
            return null;
        }
    }
    // Priority 2: Resolve 'droid' from PATH
    const isWindows = process.platform === 'win32';
    try {
        const cmd = isWindows ? 'where.exe droid' : 'which droid';
        const result = (0, child_process_1.execSync)(cmd, {
            encoding: 'utf8',
            stdio: ['ignore', 'pipe', 'ignore'],
            timeout: 5000,
        }).trim();
        const matches = result
            .split('\n')
            .map((p) => p.trim())
            .filter((p) => p);
        const candidates = isWindows
            ? [
                ...matches.filter((p) => /\.(exe|cmd|bat|ps1)$/i.test(p)),
                ...matches.filter((p) => !/\.(exe|cmd|bat|ps1)$/i.test(p)),
            ]
            : matches;
        for (const candidate of candidates) {
            try {
                if (fs.statSync(candidate).isFile()) {
                    return candidate;
                }
            }
            catch {
                // Ignore unreadable or disappearing path candidates and try next one
            }
        }
    }
    catch {
        // droid not in PATH
    }
    return null;
}
exports.detectDroidCli = detectDroidCli;
/**
 * Get Droid CLI binary info for target adapter.
 */
function getDroidBinaryInfo() {
    const droidPath = detectDroidCli();
    if (!droidPath)
        return null;
    const isWindows = process.platform === 'win32';
    const needsShell = isWindows && /\.(cmd|bat|ps1)$/i.test(droidPath);
    return { path: droidPath, needsShell };
}
exports.getDroidBinaryInfo = getDroidBinaryInfo;
/**
 * Check Droid CLI version for compatibility warnings.
 * Non-blocking — logs warning and continues.
 */
function checkDroidVersion(droidPath) {
    try {
        const version = (0, child_process_1.execFileSync)(droidPath, ['--version'], {
            encoding: 'utf8',
            stdio: ['ignore', 'pipe', 'ignore'],
            timeout: 5000,
        }).trim();
        // Parse semver major version
        const match = version.match(/(\d+)\.\d+\.\d+/);
        if (match) {
            const major = parseInt(match[1]);
            if (major >= 2) {
                console.warn(`[!] Droid version ${version} not verified with CCS. Config format may differ.`);
            }
        }
    }
    catch {
        // Version check is best-effort — don't block execution
    }
}
exports.checkDroidVersion = checkDroidVersion;
//# sourceMappingURL=droid-detector.js.map