import { SpawnUtil } from '../utils/spawn.js';
import { ErrorFactory } from '../../exceptions/ZintrustError.js';
import * as path from '../../node-singletons/path.js';
export const parseIntOption = (raw, name, expectation = 'positive') => {
    if (raw === undefined)
        return undefined;
    const parsed = Number.parseInt(raw, 10);
    const isValid = expectation === 'non-negative'
        ? Number.isFinite(parsed) && parsed >= 0
        : Number.isFinite(parsed) && parsed > 0;
    if (!isValid) {
        const expected = expectation === 'non-negative' ? 'a non-negative number' : 'a positive number';
        throw ErrorFactory.createCliError(`Invalid --${name} '${raw}'. Expected ${expected}.`);
    }
    return parsed;
};
export const trimOption = (value) => value?.trim();
const isWatchChild = () => process.env['ZINTRUST_PROXY_WATCH_CHILD'] === '1';
const buildWatchArgs = () => {
    const rawArgs = process.argv.slice(2);
    const filtered = rawArgs.filter((arg) => arg !== '--watch');
    return ['watch', path.join('bin', 'zin.ts'), ...filtered];
};
export const maybeRunProxyWatchMode = async (watch) => {
    if (watch !== true || isWatchChild())
        return;
    const args = buildWatchArgs();
    const exitCode = await SpawnUtil.spawnAndWait({
        command: 'tsx',
        args,
        env: {
            ...process.env,
            ZINTRUST_PROXY_WATCH_CHILD: '1',
        },
        forwardSignals: false,
    });
    process.exit(exitCode);
};
