import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { Box, Text } from 'ink';
import { join } from 'path';
import React from 'react';
import { ErrorMessage } from '../components/message-box.js';
import { TitledBoxWithPreferences } from '../components/ui/titled-box.js';
import { getColors } from '../config/index.js';
import { useTerminalWidth } from '../hooks/useTerminalWidth.js';
import { AgentsTemplateGenerator } from '../init/agents-template-generator.js';
import { ExistingRulesExtractor } from '../init/existing-rules-extractor.js';
import { ProjectAnalyzer } from '../init/project-analyzer.js';
import { generateKey } from '../session/key-generator.js';
import { formatError } from '../utils/error-formatter.js';
function InitSuccess({ created, analysis, }) {
    const colors = getColors();
    const boxWidth = useTerminalWidth();
    return (_jsxs(TitledBoxWithPreferences, { title: "Project Initialized", width: boxWidth, borderColor: colors.primary, paddingX: 2, paddingY: 1, flexDirection: "column", marginBottom: 1, children: [_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: colors.primary, bold: true, children: "\u2713 Nanocoder project initialized successfully!" }) }), analysis && (_jsxs(_Fragment, { children: [_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: colors.text, bold: true, children: "Project Analysis:" }) }), _jsxs(Text, { color: colors.secondary, children: ["\u2022 Type: ", analysis.projectType] }), _jsxs(Text, { color: colors.secondary, children: ["\u2022 Primary Language: ", analysis.primaryLanguage] }), analysis.frameworks.length > 0 && (_jsxs(Text, { color: colors.secondary, children: ["\u2022 Frameworks: ", analysis.frameworks.slice(0, 3).join(', ')] })), _jsxs(Text, { color: colors.secondary, children: ["\u2022 Files Analyzed: ", analysis.totalFiles] }), _jsx(Box, { marginBottom: 1 })] })), _jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: colors.text, bold: true, children: "Files Created:" }) }), created.map((item, index) => (_jsxs(Text, { color: colors.secondary, children: ["\u2022 ", item] }, index))), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: colors.text, children: "Your project is now ready for AI-assisted development!" }) }), _jsx(Text, { color: colors.secondary, children: "The AGENTS.md file will help AI understand your project context." })] })] }));
}
function InitError({ message }) {
    return _jsx(ErrorMessage, { hideBox: true, message: `✗ ${message}` });
}
export const initCommand = {
    name: 'init',
    description: 'Initialize nanocoder configuration and analyze project structure. Use --force to regenerate AGENTS.md, --lean to skip CLAUDE.md when generating AGENTS.md.',
    handler: (args, _messages, _metadata) => {
        const cwd = process.cwd();
        const created = [];
        const forceRegenerate = args.includes('--force') || args.includes('-f');
        // --lean: skip Claude-Code-specific source files (CLAUDE.md) when
        // generating AGENTS.md. Keeps the generated AGENTS.md smaller and
        // reduces duplication for users who already have CLAUDE.md.
        const lean = args.includes('--lean');
        try {
            // Check if already initialized
            const agentsPath = join(cwd, 'AGENTS.md');
            const nanocoderDir = join(cwd, '.nanocoder');
            // Check for existing initialization
            const hasAgents = existsSync(agentsPath);
            const hasNanocoder = existsSync(nanocoderDir);
            if (hasAgents && hasNanocoder && !forceRegenerate) {
                return Promise.resolve(React.createElement(InitError, {
                    key: generateKey('init-error'),
                    message: 'Project already initialized. Found AGENTS.md and .nanocoder/ directory. Use /init --force to regenerate.',
                }));
            }
            // Show progress indicator for analysis
            // Note: In a real implementation, we'd want to show this as a loading state
            // For now, we'll do the analysis synchronously
            // Analyze the project
            const analyzer = new ProjectAnalyzer(cwd);
            const analysis = analyzer.analyze();
            // Extract existing AI configuration files (skip AGENTS.md when force
            // regenerating; skip CLAUDE.md in lean mode).
            const rulesExtractor = new ExistingRulesExtractor(cwd, forceRegenerate, lean ? ['CLAUDE.md'] : []);
            const existingRules = rulesExtractor.extractExistingRules();
            // Create AGENTS.md based on analysis and existing rules
            if (!hasAgents || forceRegenerate) {
                const agentsContent = AgentsTemplateGenerator.generateAgentsMd(analysis, existingRules);
                writeFileSync(agentsPath, agentsContent);
                created.push(hasAgents ? 'AGENTS.md (regenerated)' : 'AGENTS.md');
                // Report found existing rules
                if (existingRules.length > 0) {
                    const sourceFiles = existingRules.map(r => r.source).join(', ');
                    created.push(`↳ Merged content from: ${sourceFiles}`);
                }
            }
            if (!hasNanocoder) {
                mkdirSync(nanocoderDir, { recursive: true });
                created.push('.nanocoder/');
            }
            // Prepare analysis summary for display
            const analysisSummary = {
                projectType: analysis.projectType,
                primaryLanguage: analysis.languages.primary?.name || 'Unknown',
                frameworks: analysis.dependencies.frameworks.map((f) => f.name),
                totalFiles: analysis.structure.scannedFiles,
            };
            return Promise.resolve(React.createElement(InitSuccess, {
                key: generateKey('init-success'),
                created,
                analysis: analysisSummary,
            }));
        }
        catch (error) {
            const errorMessage = formatError(error);
            return Promise.resolve(React.createElement(InitError, {
                key: generateKey('init-error'),
                message: `Failed to initialize project: ${errorMessage}`,
            }));
        }
    },
};
//# sourceMappingURL=init.js.map