"use strict";
/**
 * Interactive Prompt Utilities
 * Issue #119: Interactive init support
 *
 * Provides readline-based prompts for CLI commands.
 * Reference implementation: scripts/setup-env.sh
 */
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.closeReadline = closeReadline;
exports.expandTilde = expandTilde;
exports.resolvePath = resolvePath;
exports.validatePort = validatePort;
exports.prompt = prompt;
exports.confirm = confirm;
exports.isInteractive = isInteractive;
const readline = __importStar(require("readline"));
const os_1 = require("os");
const path_1 = require("path");
/**
 * Readline interface singleton
 * Reused across prompts to avoid creating multiple interfaces
 */
let rlInstance = null;
/**
 * Get or create readline interface
 */
function getReadlineInterface() {
    if (!rlInstance) {
        rlInstance = readline.createInterface({
            input: process.stdin,
            output: process.stdout,
        });
    }
    return rlInstance;
}
/**
 * Close readline interface
 * Should be called when all prompts are done
 */
function closeReadline() {
    if (rlInstance) {
        rlInstance.close();
        rlInstance = null;
    }
}
/**
 * Expand tilde (~) to home directory
 *
 * @param path - Path that may contain tilde
 * @returns Path with tilde expanded to home directory
 *
 * @example
 * expandTilde('~/repos') // '/Users/xxx/repos'
 * expandTilde('/absolute/path') // '/absolute/path'
 */
function expandTilde(path) {
    if (path.startsWith('~/')) {
        return path.replace(/^~/, (0, os_1.homedir)());
    }
    if (path === '~') {
        return (0, os_1.homedir)();
    }
    return path;
}
/**
 * Resolve path to absolute path
 * Handles tilde expansion and relative paths
 *
 * @param path - Path to resolve
 * @returns Absolute path
 */
function resolvePath(path) {
    const expanded = expandTilde(path);
    return (0, path_1.resolve)(expanded);
}
/**
 * Validate port number
 *
 * @param input - Port number as string
 * @returns Error message or true if valid
 */
function validatePort(input) {
    const port = parseInt(input, 10);
    if (isNaN(port)) {
        return 'Port must be a number';
    }
    if (port < 1 || port > 65535) {
        return 'Port must be between 1 and 65535';
    }
    return true;
}
/**
 * Interactive prompt with default value and validation
 *
 * @param question - Question to display
 * @param options - Prompt options (default, validate)
 * @returns User input or default value
 *
 * @example
 * const port = await prompt('Server port', { default: '3000', validate: validatePort });
 */
async function prompt(question, options = {}) {
    const rl = getReadlineInterface();
    const { default: defaultValue, validate } = options;
    const displayQuestion = defaultValue
        ? `? ${question} [${defaultValue}]: `
        : `? ${question}: `;
    return new Promise((resolvePromise) => {
        const askQuestion = () => {
            rl.question(displayQuestion, (answer) => {
                const trimmedAnswer = answer.trim();
                const result = trimmedAnswer || defaultValue || '';
                // Validate if validator provided
                if (validate && result) {
                    const validationResult = validate(result);
                    if (validationResult !== true) {
                        console.log(`  Error: ${validationResult}`);
                        askQuestion(); // Re-ask
                        return;
                    }
                }
                resolvePromise(result);
            });
        };
        askQuestion();
    });
}
/**
 * Interactive Yes/No confirmation
 *
 * @param question - Question to display
 * @param options - Confirm options (default)
 * @returns true for Yes, false for No
 *
 * @example
 * const enableExternal = await confirm('Enable external access?', { default: false });
 */
async function confirm(question, options = {}) {
    const rl = getReadlineInterface();
    const defaultValue = options.default ?? false;
    const hint = defaultValue ? '(Y/n)' : '(y/N)';
    const displayQuestion = `? ${question} ${hint}: `;
    return new Promise((resolvePromise) => {
        const askQuestion = () => {
            rl.question(displayQuestion, (answer) => {
                const trimmedAnswer = answer.trim().toLowerCase();
                if (trimmedAnswer === '') {
                    resolvePromise(defaultValue);
                    return;
                }
                if (trimmedAnswer === 'y' || trimmedAnswer === 'yes') {
                    resolvePromise(true);
                    return;
                }
                if (trimmedAnswer === 'n' || trimmedAnswer === 'no') {
                    resolvePromise(false);
                    return;
                }
                // Invalid input - re-ask
                console.log('  Please answer with y/n or yes/no');
                askQuestion();
            });
        };
        askQuestion();
    });
}
/**
 * Check if running in interactive mode (TTY)
 *
 * @returns true if stdin is a TTY (interactive terminal)
 */
function isInteractive() {
    return process.stdin.isTTY === true;
}
