"use strict";
/**
 * Project Selection Handler
 *
 * Manages interactive project selection prompts during OAuth flow.
 * Parses CLIProxyAPI stdout for project lists and coordinates
 * between backend (stdin writer) and frontend (WebSocket/UI).
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasPendingSelection = exports.getPendingSelection = exports.cancelProjectSelection = exports.submitProjectSelection = exports.requestProjectSelection = exports.generateSessionId = exports.isProjectList = exports.isProjectSelectionPrompt = exports.parseDefaultProject = exports.parseProjectList = exports.projectSelectionEvents = void 0;
const events_1 = require("events");
// Global event emitter for project selection events
exports.projectSelectionEvents = new events_1.EventEmitter();
// Pending selections by session ID
const pendingSelections = new Map();
// Default timeout for project selection (30 seconds)
const SELECTION_TIMEOUT_MS = 30000;
/**
 * Parse project list from CLIProxyAPI stdout
 *
 * Expected format:
 * "Available Google Cloud projects:
 *  [1] project-id-123 (Project Name)
 *  [2] another-project (Another Name)
 *  Type 'ALL' to onboard every listed project."
 */
function parseProjectList(output) {
    const projects = [];
    // Match lines like: [1] project-id (Project Name)
    const projectRegex = /\[(\d+)\]\s+(\S+)\s+\(([^)]+)\)/g;
    let match;
    while ((match = projectRegex.exec(output)) !== null) {
        projects.push({
            index: parseInt(match[1], 10),
            id: match[2],
            name: match[3],
        });
    }
    return projects;
}
exports.parseProjectList = parseProjectList;
/**
 * Parse default project ID from prompt
 *
 * Expected format: "Enter project ID [default-project-id] or ALL:"
 */
function parseDefaultProject(output) {
    const match = output.match(/Enter project ID \[([^\]]+)\] or ALL:/);
    return match ? match[1] : null;
}
exports.parseDefaultProject = parseDefaultProject;
/**
 * Check if output contains project selection prompt
 */
function isProjectSelectionPrompt(output) {
    return output.includes('Enter project ID') && output.includes('or ALL:');
}
exports.isProjectSelectionPrompt = isProjectSelectionPrompt;
/**
 * Check if output contains project list
 */
function isProjectList(output) {
    return output.includes('Available Google Cloud projects:');
}
exports.isProjectList = isProjectList;
/**
 * Generate unique session ID for OAuth flow
 */
function generateSessionId() {
    return `auth-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
}
exports.generateSessionId = generateSessionId;
/**
 * Request project selection from UI
 * Returns promise that resolves when user selects a project
 *
 * @param prompt - Project selection prompt data
 * @returns Promise<string> - Selected project ID or 'ALL', or default if timeout
 */
function requestProjectSelection(prompt) {
    return new Promise((resolve) => {
        // Set timeout for auto-selection
        const timeout = setTimeout(() => {
            const pending = pendingSelections.get(prompt.sessionId);
            if (pending) {
                pendingSelections.delete(prompt.sessionId);
                // Auto-select default on timeout
                resolve(prompt.defaultProjectId);
                exports.projectSelectionEvents.emit('selection:timeout', prompt.sessionId);
            }
        }, SELECTION_TIMEOUT_MS);
        // Store pending selection
        pendingSelections.set(prompt.sessionId, {
            prompt,
            resolve,
            timeout,
        });
        // Emit event for WebSocket broadcast
        exports.projectSelectionEvents.emit('selection:required', prompt);
    });
}
exports.requestProjectSelection = requestProjectSelection;
/**
 * Submit project selection from UI
 *
 * @param response - Selection response with session ID and selected project
 * @returns boolean - True if selection was accepted
 */
function submitProjectSelection(response) {
    const pending = pendingSelections.get(response.sessionId);
    if (!pending) {
        return false;
    }
    // Clear timeout and remove from pending
    clearTimeout(pending.timeout);
    pendingSelections.delete(response.sessionId);
    // Resolve the promise with selected ID
    pending.resolve(response.selectedId);
    exports.projectSelectionEvents.emit('selection:submitted', response);
    return true;
}
exports.submitProjectSelection = submitProjectSelection;
/**
 * Cancel pending project selection
 */
function cancelProjectSelection(sessionId) {
    const pending = pendingSelections.get(sessionId);
    if (!pending) {
        return false;
    }
    clearTimeout(pending.timeout);
    pendingSelections.delete(sessionId);
    // Resolve with default (empty string to auto-select)
    pending.resolve('');
    exports.projectSelectionEvents.emit('selection:cancelled', sessionId);
    return true;
}
exports.cancelProjectSelection = cancelProjectSelection;
/**
 * Get pending project selection prompt
 */
function getPendingSelection(sessionId) {
    const pending = pendingSelections.get(sessionId);
    return pending ? pending.prompt : null;
}
exports.getPendingSelection = getPendingSelection;
/**
 * Check if there's a pending selection
 */
function hasPendingSelection(sessionId) {
    return pendingSelections.has(sessionId);
}
exports.hasPendingSelection = hasPendingSelection;
exports.default = {
    parseProjectList,
    parseDefaultProject,
    isProjectSelectionPrompt,
    isProjectList,
    generateSessionId,
    requestProjectSelection,
    submitProjectSelection,
    cancelProjectSelection,
    getPendingSelection,
    hasPendingSelection,
    projectSelectionEvents: exports.projectSelectionEvents,
};
//# sourceMappingURL=project-selection-handler.js.map