import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { Box, Text } from 'ink';
import { useEffect, useState, useCallback } from 'react';
import { theme } from '../semantic-colors.js';
import stripAnsi from 'strip-ansi';
import { RadioButtonSelect, } from './shared/RadioButtonSelect.js';
import { MaxSizedBox } from './shared/MaxSizedBox.js';
import { Scrollable } from './shared/Scrollable.js';
import { useKeypress } from '../hooks/useKeypress.js';
import * as process from 'node:process';
import * as path from 'node:path';
import { relaunchApp } from '../../utils/processUtils.js';
import { runExitCleanup } from '../../utils/cleanup.js';
import { ExitCodes, } from '@google/gemini-cli-core';
import { useUIState } from '../contexts/UIStateContext.js';
import { useAlternateBuffer } from '../hooks/useAlternateBuffer.js';
import { OverflowProvider } from '../contexts/OverflowContext.js';
import { ShowMoreLines } from './ShowMoreLines.js';
import { StickyHeader } from './StickyHeader.js';
export var FolderTrustChoice;
(function (FolderTrustChoice) {
    FolderTrustChoice["TRUST_FOLDER"] = "trust_folder";
    FolderTrustChoice["TRUST_PARENT"] = "trust_parent";
    FolderTrustChoice["DO_NOT_TRUST"] = "do_not_trust";
})(FolderTrustChoice || (FolderTrustChoice = {}));
export const FolderTrustDialog = ({ onSelect, isRestarting, discoveryResults, }) => {
    const [exiting, setExiting] = useState(false);
    const { terminalHeight, terminalWidth, constrainHeight } = useUIState();
    const isAlternateBuffer = useAlternateBuffer();
    const isExpanded = !constrainHeight;
    useEffect(() => {
        let timer;
        if (isRestarting) {
            timer = setTimeout(relaunchApp, 250);
        }
        return () => {
            if (timer)
                clearTimeout(timer);
        };
    }, [isRestarting]);
    const handleExit = useCallback(() => {
        setExiting(true);
        // Give time for the UI to render the exiting message
        setTimeout(async () => {
            await runExitCleanup();
            process.exit(ExitCodes.FATAL_CANCELLATION_ERROR);
        }, 100);
    }, []);
    useKeypress((key) => {
        if (key.name === 'escape') {
            handleExit();
            return true;
        }
        return false;
    }, { isActive: !isRestarting });
    const dirName = path.basename(process.cwd());
    const parentFolder = path.basename(path.dirname(process.cwd()));
    const options = [
        {
            label: `Trust folder (${dirName})`,
            value: FolderTrustChoice.TRUST_FOLDER,
            key: `Trust folder (${dirName})`,
        },
        {
            label: `Trust parent folder (${parentFolder})`,
            value: FolderTrustChoice.TRUST_PARENT,
            key: `Trust parent folder (${parentFolder})`,
        },
        {
            label: "Don't trust",
            value: FolderTrustChoice.DO_NOT_TRUST,
            key: "Don't trust",
        },
    ];
    const hasDiscovery = discoveryResults &&
        (discoveryResults.commands.length > 0 ||
            discoveryResults.mcps.length > 0 ||
            discoveryResults.hooks.length > 0 ||
            discoveryResults.skills.length > 0 ||
            discoveryResults.settings.length > 0);
    const hasWarnings = discoveryResults && discoveryResults.securityWarnings.length > 0;
    const hasErrors = discoveryResults &&
        discoveryResults.discoveryErrors &&
        discoveryResults.discoveryErrors.length > 0;
    const dialogWidth = terminalWidth - 2;
    const borderColor = theme.status.warning;
    // Header: 3 lines
    // Options: options.length + 2 lines for margins
    // Footer: 1 line
    // Safety margin: 2 lines
    const overhead = 3 + options.length + 2 + 1 + 2;
    const scrollableHeight = Math.max(4, terminalHeight - overhead);
    const groups = [
        { label: 'Commands', items: discoveryResults?.commands ?? [] },
        { label: 'MCP Servers', items: discoveryResults?.mcps ?? [] },
        { label: 'Hooks', items: discoveryResults?.hooks ?? [] },
        { label: 'Skills', items: discoveryResults?.skills ?? [] },
        { label: 'Agents', items: discoveryResults?.agents ?? [] },
        { label: 'Setting overrides', items: discoveryResults?.settings ?? [] },
    ].filter((g) => g.items.length > 0);
    const discoveryContent = (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: theme.text.primary, children: "Trusting a folder allows Gemini CLI to load its local configurations, including custom commands, hooks, MCP servers, agent skills, and settings. These configurations could execute code on your behalf or change the behavior of the CLI." }) }), hasErrors && (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: theme.status.error, bold: true, children: "\u274C Discovery Errors:" }), discoveryResults.discoveryErrors.map((error, i) => (_jsx(Box, { marginLeft: 2, children: _jsxs(Text, { color: theme.status.error, children: ["\u2022 ", stripAnsi(error)] }) }, i)))] })), hasWarnings && (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: theme.status.warning, bold: true, children: "\u26A0\uFE0F Security Warnings:" }), discoveryResults.securityWarnings.map((warning, i) => (_jsx(Box, { marginLeft: 2, children: _jsxs(Text, { color: theme.status.warning, children: ["\u2022 ", stripAnsi(warning)] }) }, i)))] })), hasDiscovery && (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: theme.text.primary, bold: true, children: "This folder contains:" }), groups.map((group) => (_jsxs(Box, { flexDirection: "column", marginLeft: 2, children: [_jsxs(Text, { color: theme.text.primary, bold: true, children: ["\u2022 ", group.label, " (", group.items.length, "):"] }), group.items.map((item, idx) => (_jsx(Box, { marginLeft: 2, children: _jsxs(Text, { color: theme.text.primary, children: ["- ", stripAnsi(item)] }) }, idx)))] }, group.label)))] }))] }));
    const title = (_jsx(Text, { bold: true, color: theme.text.primary, children: "Do you trust the files in this folder?" }));
    const selectOptions = (_jsx(RadioButtonSelect, { items: options, onSelect: onSelect, isFocused: !isRestarting }));
    const renderContent = () => {
        if (isAlternateBuffer) {
            return (_jsxs(Box, { flexDirection: "column", width: dialogWidth, children: [_jsx(StickyHeader, { width: dialogWidth, isFirst: true, borderColor: borderColor, borderDimColor: false, children: title }), _jsxs(Box, { flexDirection: "column", borderLeft: true, borderRight: true, borderColor: borderColor, borderStyle: "round", borderTop: false, borderBottom: false, width: dialogWidth, children: [_jsx(Scrollable, { hasFocus: !isRestarting, height: scrollableHeight, width: dialogWidth - 2, children: _jsx(Box, { flexDirection: "column", paddingX: 1, children: discoveryContent }) }), _jsx(Box, { paddingX: 1, marginY: 1, children: selectOptions })] }), _jsx(Box, { height: 0, width: dialogWidth, borderLeft: true, borderRight: true, borderTop: false, borderBottom: true, borderColor: borderColor, borderStyle: "round" })] }));
        }
        return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: borderColor, padding: 1, width: "100%", children: [_jsx(Box, { marginBottom: 1, children: title }), _jsx(MaxSizedBox, { maxHeight: isExpanded ? undefined : Math.max(4, terminalHeight - 12), overflowDirection: "bottom", children: discoveryContent }), _jsx(Box, { marginTop: 1, children: selectOptions })] }));
    };
    const content = (_jsxs(Box, { flexDirection: "column", width: "100%", children: [_jsx(Box, { flexDirection: "column", marginLeft: 1, marginRight: 1, children: renderContent() }), _jsx(Box, { paddingX: 2, marginBottom: 1, children: _jsx(ShowMoreLines, { constrainHeight: constrainHeight }) }), isRestarting && (_jsx(Box, { marginLeft: 1, marginTop: 1, children: _jsx(Text, { color: theme.status.warning, children: "Gemini CLI is restarting to apply the trust changes..." }) })), exiting && (_jsx(Box, { marginLeft: 1, marginTop: 1, children: _jsx(Text, { color: theme.status.warning, children: "A folder trust level must be selected to continue. Exiting since escape was pressed." }) }))] }));
    return _jsx(OverflowProvider, { children: content });
};
//# sourceMappingURL=FolderTrustDialog.js.map