#!/usr/bin/env node
"use strict";
/**
 * Farm Runner CLI
 *
 * Main entry point for the farm-runner CLI tool
 *
 * Usage:
 *   farm-runner [command] [options]
 *
 * Commands:
 *   start              Start the node server (default)
 *   --help, -h         Show help message
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
/**
 * Get version from package.json
 */
function getVersion() {
    try {
        // Try to read from the package directory (works in both dev and production)
        const packagePath = path_1.default.join(__dirname, '../../package.json');
        if (fs_1.default.existsSync(packagePath)) {
            const packageJson = JSON.parse(fs_1.default.readFileSync(packagePath, 'utf-8'));
            return packageJson.version || 'unknown';
        }
        // Fallback: try to read from process.env (set by npm)
        return process.env.npm_package_version || 'unknown';
    }
    catch (error) {
        return 'unknown';
    }
}
/**
 * Show version
 */
function showVersion() {
    const version = getVersion();
    console.log(version);
}
/**
 * Parse CLI arguments
 */
function parseArgs() {
    const args = process.argv.slice(2);
    if (args.length === 0 || args[0] === 'start') {
        return { command: 'start', args: args.slice(1) };
    }
    if (args[0] === 'doctor') {
        return { command: 'doctor', args: args.slice(1) };
    }
    if (args[0] === '--help' || args[0] === '-h') {
        return { command: 'help', args: [] };
    }
    if (args[0] === '--version' || args[0] === '-v') {
        return { command: 'version', args: [] };
    }
    // If no recognized command, treat as start with all args
    return { command: 'start', args };
}
/**
 * ANSI helpers — emit codes only when stdout is a TTY so piped output stays plain.
 */
const _tty = process.stdout.isTTY;
const _ansi = (code, s) => (_tty ? `\x1b[${code}m${s}\x1b[0m` : s);
const C = {
    title: (s) => _ansi('1;36', s), // bold cyan
    hdr: (s) => _ansi('1;33', s), // bold yellow
    cmd: (s) => _ansi('36', s), // cyan
    flag: (s) => _ansi('32', s), // green
    url: (s) => _ansi('4;36', s), // underlined cyan
    dim: (s) => _ansi('2', s), // dim
    warn: (s) => _ansi('33', s), // yellow
};
/**
 * Show help message
 */
function showHelp() {
    console.log(`
${C.title('Farm Runner')} ${C.dim('— Device Farm Node Server')}

${C.hdr('Usage:')}
  ${C.cmd('farm-runner')} [command] [options]

${C.hdr('Commands:')}
  ${C.cmd('start')}                          Start the node server (default)
  ${C.cmd('doctor')} [options]               Verify all required dependencies are installed
  ${C.flag('--help, -h')}                     Show this help message
  ${C.flag('--version, -v')}                  Show version information

${C.hdr('Start options')} ${C.dim('(can also come from --config file or env vars):')}
  ${C.flag('--config, -c')} <path>            Path to node.config.json ${C.dim('(default: ./node.config.json in cwd)')}
  ${C.flag('--hub-url, -u')} <url>            Hub WebSocket URL, e.g. http://hub.local:3000
  ${C.flag('--access-key, -a')} <key>         Access key issued by the hub
  ${C.flag('--token, -t')} <token>            Auth token issued by the hub
  ${C.flag('--name, -n')} <name>              Friendly name for this node ${C.dim('(default: hostname)')}
  ${C.flag('--host')} <host:port>             Override the host:port advertised to the hub
  ${C.flag('--os')} <android|ios|both>        Platforms this node serves
  ${C.flag('--tags')} <csv>                   Comma-separated tags for capability matching
  ${C.flag('--temp-logs-dir')} <path>         Where to buffer session logs before upload

${C.hdr('Doctor options:')}
  ${C.flag('--platform')} <android|ios|both>  Limit checks to one platform ${C.dim('(default: both on macOS, android elsewhere)')}
  ${C.flag('--hub-url')} <url>                Also probe reachability of the given hub URL

${C.hdr('Examples:')}
  ${C.dim('# 1) Start with a config file (recommended)')}
  ${C.cmd('farm-runner start')} ${C.flag('--config')} ./node.config.json

  ${C.dim('# 2) Start with inline flags')}
  ${C.cmd('farm-runner start')} \\
    ${C.flag('--hub-url')} http://hub.local:3000 \\
    ${C.flag('--access-key')} abc123 \\
    ${C.flag('--token')} tk_xyz \\
    ${C.flag('--name')} mac-mini-01 \\
    ${C.flag('--os')} both

  ${C.dim('# 3) Health check')}
  ${C.cmd('farm-runner doctor')}
  ${C.cmd('farm-runner doctor')} ${C.flag('--platform')} ios
  ${C.cmd('farm-runner doctor')} ${C.flag('--hub-url')} http://localhost:3000

${C.hdr('Example node.config.json:')}
  {
    "hubUrl": "http://hub.local:3000",
    "accessKey": "your-access-key",
    "token": "your-token",
    "name": "mac-mini-01",
    "platform": "both",
    "iosDeviceType": "both",
    "androidDeviceType": "both",
    "bootedSimulators": false,
    "tags": "team-mobile,perf-rigs",
    "tempLogsDir": "./tmp",
    "capabilityPortRange": { "min": 4723, "max": 4823 },
    "appiumServer": {
      "enabled": true,
      "serverArgs": {
        "port": 4723,
        "address": "0.0.0.0",
        "relaxed-security": true,
        "log-level": "info"
      }
    },
    "scrcpy": {
      "enabled": true,
      "maxFps": 30,
      "maxSize": 1280,
      "videoBitRate": 2000000
    },
    "mjpeg": {
      "width": 1280,
      "height": 720,
      "fps": 24,
      "bitrate": "1500k",
      "preset": "ultrafast"
    },
    "deviceReconciliation": { "enabled": true, "intervalMs": 60000 },
    "androidCleanUpApps": ["com.example.app1"],
    "iosCleanUpApps":     ["com.example.app1"]
  }

${C.hdr('Notes:')}
  ${C.warn('•')} Only ${C.flag('hubUrl')} + ${C.flag('accessKey')} + ${C.flag('token')} are required; everything else has a sensible default.
  ${C.warn('•')} CLI flags override the config file. Run ${C.cmd('farm-runner doctor')} first to verify deps.

${C.dim('Docs & more:')} ${C.url('https://farmly.dev')}
  `);
}
/**
 * Start the node server
 */
function startServer(args) {
    // In production, use the bundled version if available
    // In development, fall back to server.js
    const bundlePath = path_1.default.join(__dirname, 'bundle.js');
    const serverPath = path_1.default.join(__dirname, 'server.js');
    const targetPath = fs_1.default.existsSync(bundlePath) ? bundlePath : serverPath;
    const child = (0, child_process_1.spawn)('node', [targetPath, ...args], {
        stdio: 'inherit',
        env: process.env,
    });
    child.on('exit', code => {
        process.exit(code || 0);
    });
}
/**
 * Parse `--platform <value>` / `--hub-url <value>` style flags for the doctor subcommand.
 */
function parseDoctorFlags(args) {
    const result = {};
    for (let i = 0; i < args.length; i++) {
        const a = args[i];
        if (a === '--platform' && i + 1 < args.length) {
            const v = args[i + 1];
            if (v === 'android' || v === 'ios' || v === 'both')
                result.platform = v;
            i += 1;
        }
        else if (a === '--hub-url' && i + 1 < args.length) {
            result.hubUrl = args[i + 1];
            i += 1;
        }
    }
    return result;
}
/**
 * Run the doctor health check in-process (no spawn) so output streams directly.
 */
function runDoctor(args) {
    const flags = parseDoctorFlags(args);
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const { runNodeDoctor } = require('./doctor');
    runNodeDoctor(flags)
        .then((code) => process.exit(code))
        .catch((err) => {
        console.error('Doctor failed:', err);
        process.exit(1);
    });
}
/**
 * Main CLI handler
 */
function main() {
    const { command, args } = parseArgs();
    switch (command) {
        case 'help':
            showHelp();
            process.exit(0);
            break;
        case 'version':
            showVersion();
            process.exit(0);
            break;
        case 'doctor':
            runDoctor(args);
            break;
        case 'start':
            startServer(args);
            break;
        default:
            console.error(`❌ Unknown command: ${command}`);
            console.log('Run "farm-runner --help" for usage information.');
            process.exit(1);
    }
}
// Run the CLI
main();
//# sourceMappingURL=cli.js.map