"use strict";
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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InitCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const prompts_1 = __importDefault(require("prompts"));
const inquirer_1 = __importDefault(require("inquirer"));
const clipboardy_1 = __importDefault(require("clipboardy"));
const figlet_1 = __importDefault(require("figlet"));
const gradient_string_1 = __importDefault(require("gradient-string"));
const spinner_1 = require("../utils/spinner");
const fileSystem_1 = require("../utils/fileSystem");
const child_process_1 = require("child_process");
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const core_1 = require("@myycontext/core");
const workspace_1 = require("../utils/workspace");
class InitCommand {
    constructor() {
        this.fs = new fileSystem_1.FileSystemManager();
        this.manifestManager = new core_1.DesignManifestManager();
    }
    async execute(projectName, options) {
        const spinner = new spinner_1.EnhancedSpinner("Initializing...");
        try {
            this.displayBranding();
            const currentDir = process.cwd();
            const currentDirName = path.basename(currentDir);
            const hasPackageJson = await fs.pathExists(path.join(currentDir, "package.json"));
            const mycontextPath = path.join(currentDir, ".mycontext");
            const hasMyContext = await fs.pathExists(mycontextPath);
            const workspaceManager = new workspace_1.WorkspaceManager(currentDir);
            const isMonorepo = await workspaceManager.isMonorepo();
            let selectedScopes = options.scope ? options.scope.split(',').map(s => s.trim()) : undefined;
            const ignorePatterns = options.ignore ? options.ignore.split(',').map(i => i.trim()) : undefined;
            // Collect all interactive configuration upfront
            let i18nConfig = await this.askI18nConfig(options);
            // Monorepo selection logic
            if (isMonorepo && !selectedScopes && !options.yes) {
                console.log(chalk_1.default.cyan("\n📦 Monorepo detected! Choose the scope for this context:"));
                const workspaces = await workspaceManager.getWorkspaces();
                const { scopeChoice } = await (0, prompts_1.default)({
                    type: "multiselect",
                    name: "scopeChoice",
                    message: "Select workspaces/directories to include (Space to select, Enter to confirm):",
                    choices: [
                        { title: "Full Monorepo (Root)", value: "root", selected: true },
                        ...workspaces.map(ws => ({
                            title: `${ws.name} (${ws.path})`,
                            value: ws.path
                        }))
                    ],
                    hint: "- Root includes everything. Specific workspaces limit the scope."
                });
                if (scopeChoice && !scopeChoice.includes("root")) {
                    selectedScopes = scopeChoice;
                    // Smart Scoping: Suggest related packages
                    if (selectedScopes && selectedScopes.length === 1) {
                        const related = await workspaceManager.getRelatedPackages(path.join(currentDir, selectedScopes[0]));
                        if (related.length > 0) {
                            const { addRelated } = await (0, prompts_1.default)({
                                type: "confirm",
                                name: "addRelated",
                                message: `Found ${related.length} shared packages used by this app. Include them too?`,
                                initial: true
                            });
                            if (addRelated) {
                                selectedScopes.push(...related.map(r => r.path));
                            }
                        }
                    }
                }
            }
            // Handle project name resolution
            let finalProjectName = projectName;
            let useCurrentDir = projectName === "." || !projectName;
            if (useCurrentDir) {
                finalProjectName = currentDirName;
            }
            // 1. Existing Project Flow (package.json exists)
            if (hasPackageJson && !options.next && !options.framework && !options.specOnly) {
                const isInteractive = !options.yes;
                let shouldInitialize = true;
                if (isInteractive) {
                    const { useExisting } = await (0, prompts_1.default)({
                        type: "confirm",
                        name: "useExisting",
                        message: chalk_1.default.yellow(`⚠️  Existing project detected (${finalProjectName || "this directory"}). Initialize MyContext here?`),
                        initial: true
                    });
                    shouldInitialize = useExisting;
                }
                if (shouldInitialize) {
                    let initMode = "scan";
                    if (isInteractive) {
                        const response = await (0, prompts_1.default)({
                            type: "select",
                            name: "initMode",
                            message: "How would you like to initialize context?",
                            choices: [
                                { title: "Scan Project (Recommended)", value: "scan", description: "Analyzes file tree & key files to build context" },
                                { title: "Manual Input", value: "manual", description: "Enter project description yourself" }
                            ],
                            initial: 0
                        });
                        initMode = response.initMode;
                    }
                    let description = options.description || `${finalProjectName || "app"} - AI-powered app`;
                    if (initMode === "scan") {
                        spinner.start();
                        spinner.updateText("Scanning project structure...");
                        const scanStart = Date.now();
                        try {
                            const { ProjectScanner } = await Promise.resolve().then(() => __importStar(require("../services/ProjectScanner")));
                            const scanner = new ProjectScanner(currentDir);
                            const snapshot = await scanner.scan((progress) => {
                                spinner.updateText(progress);
                            });
                            const scanMs = Date.now() - scanStart;
                            spinner.updateText(`Scan complete (${snapshot.stats.totalFiles} files in ${(scanMs / 1000).toFixed(1)}s)`);
                            // Extract README content for grounding if available
                            const readme = snapshot.keyFiles.find(f => f.path.toLowerCase().includes("readme.md"));
                            const docSummary = readme ? `\n\nGROUNDING DOC (README):\n${readme.content.substring(0, 2500)}` : "";
                            description = `Project: ${finalProjectName || "unknown"}\nStats: ${snapshot.stats.totalFiles} files, ${snapshot.stats.componentFiles} components, ${snapshot.stats.routeFiles} routes.${docSummary}\nContext: ${options.description || ''}`;
                        }
                        catch (e) {
                            // fallback
                            spinner.updateText("Scan failed, using defaults...");
                        }
                        spinner.stop();
                    }
                    else if (initMode === "manual" && !options.description && isInteractive) {
                        const { inputMethod } = await inquirer_1.default.prompt([
                            {
                                type: "list",
                                name: "inputMethod",
                                message: "How would you like to provide the project description?",
                                choices: [
                                    { name: "📋 Paste from Clipboard (Best for long PRDs)", value: "clipboard" },
                                    { name: "📝 Open Default Editor (Vim/Nano)", value: "editor" },
                                    { name: "⌨️  Type Simple Description", value: "type" }
                                ]
                            }
                        ]);
                        if (inputMethod === "clipboard") {
                            try {
                                spinner.updateText("Reading clipboard...");
                                description = await clipboardy_1.default.read();
                                if (!description || description.trim().length === 0) {
                                    console.log(chalk_1.default.red("\n❌ Clipboard is empty. Please copy your spec first."));
                                    description = (await inquirer_1.default.prompt([{ type: "input", name: "desc", message: "Simple description:" }])).desc;
                                }
                                else {
                                    console.log(chalk_1.default.green(`\n✅ Successfully ingested ${description.length} characters from clipboard.`));
                                }
                            }
                            catch (err) {
                                console.log(chalk_1.default.red("\n❌ Failed to read clipboard. Check permissions."));
                                description = (await inquirer_1.default.prompt([{ type: "input", name: "desc", message: "Simple description:" }])).desc;
                            }
                        }
                        else if (inputMethod === "editor") {
                            const { desc } = await inquirer_1.default.prompt([
                                {
                                    type: "editor",
                                    name: "desc",
                                    message: "Project description:",
                                    validate: (value) => value.trim().length > 0 ? true : "Description is required"
                                }
                            ]);
                            description = desc;
                        }
                        else {
                            const { desc } = await inquirer_1.default.prompt([
                                {
                                    type: "input",
                                    name: "desc",
                                    message: "Simple description:",
                                    validate: (value) => value.length > 0 ? true : "Description is required"
                                }
                            ]);
                            description = desc;
                        }
                    }
                    spinner.start();
                    spinner.updateText("Writing project configuration...");
                    const config = await this.fs.initializeProject(finalProjectName, description, currentDir, true, selectedScopes, ignorePatterns, i18nConfig);
                    spinner.updateText("Creating Living Brain manifest...");
                    await this.createInitialManifest(currentDir, finalProjectName, description);
                    // Bootstrap page skeletons and routing pages
                    try {
                        spinner.updateText("Generating page skeletons and routing pages...");
                        const { SkeletonService } = await Promise.resolve().then(() => __importStar(require("../services/SkeletonService")));
                        const skeletonService = new SkeletonService(currentDir);
                        const suggestions = await skeletonService.auditSkeletons();
                        if (suggestions.length > 0) {
                            await skeletonService.ensureSkeletonComponent();
                            let generated = 0;
                            for (const s of suggestions) {
                                const ok = await skeletonService.applySuggestion(s);
                                if (ok)
                                    generated++;
                            }
                            if (generated > 0) {
                                spinner.updateText(`Generated ${generated} skeleton/routing files`);
                            }
                        }
                    }
                    catch {
                        // Non-critical — don't block init if skeleton generation fails
                    }
                    spinner.success({ text: `Project "${finalProjectName}" initialized with context!` });
                    // Post-initialization environment setup
                    await this.setupEnvironmentKeys(currentDir, options, undefined);
                    this.showNextSteps(config, undefined, true);
                    return;
                }
            }
            // 2. New Project Flow (No package.json or explicitly requested new)
            if (!hasPackageJson && !options.yes && !options.specOnly) {
                const { framework } = await (0, prompts_1.default)({
                    type: "select",
                    name: "framework",
                    message: "No package.json found. What would you like to build?",
                    choices: [
                        { title: "Next.js + InstantDB (Full Stack)", value: "instantdb" },
                        { title: "Next.js Landing Page (High Fidelity UI)", value: "landing" },
                        { title: "Next.js + shadcn (UI Only)", value: "nextjs" },
                        { title: "Basic MyContext (Spec Only)", value: "basic" }
                    ],
                    initial: 0
                });
                if (framework === "basic") {
                    options.specOnly = true;
                }
                else {
                    options.framework = framework;
                }
            }
            // Resolution for final naming if still undefined
            if (!finalProjectName && !options.yes) {
                const responses = await (0, prompts_1.default)([
                    {
                        type: "text",
                        name: "name",
                        message: "Project name:",
                        initial: currentDirName,
                        validate: (value) => value.length > 0 || "Project name is required",
                    },
                ]);
                finalProjectName = responses.name || currentDirName;
                useCurrentDir = finalProjectName === "." || finalProjectName === currentDirName;
                if (finalProjectName === ".")
                    finalProjectName = currentDirName;
            }
            if (!finalProjectName)
                finalProjectName = currentDirName || "my-app";
            const workingDir = process.cwd();
            // Safety check for overwrite / non-empty directory
            const isDirty = (await fs.readdir(workingDir)).filter(f => !f.startsWith('.')).length > 0;
            if (useCurrentDir && !hasPackageJson && isDirty && !options.force && !options.yes) {
                console.log(chalk_1.default.yellow(`⚠️  The current directory contains files that may conflict with project scaffolding.`));
                const { projectName: newName } = await (0, prompts_1.default)({
                    type: "text",
                    name: "projectName",
                    message: "Enter a new project name (to create a subdirectory):",
                    validate: (val) => val.length > 0 || "Project name is required"
                });
                if (newName && newName !== ".") {
                    finalProjectName = newName;
                    useCurrentDir = false;
                }
            }
            else if (useCurrentDir && !hasPackageJson && isDirty && options.yes) {
                console.log(chalk_1.default.gray("ℹ️  Directory is not empty, but --yes specified. Proceeding..."));
            }
            const projectPath = useCurrentDir ? workingDir : path.resolve(workingDir, finalProjectName);
            const effectiveDescription = options.description || `${finalProjectName} - AI-powered app`;
            if (await fs.pathExists(path.join(projectPath, ".mycontext")) && !options.force && !options.yes) {
                const { confirmOverwrite } = await (0, prompts_1.default)({
                    type: "confirm",
                    name: "confirmOverwrite",
                    message: chalk_1.default.yellow(`⚠️  Existing .mycontext folder found in ${useCurrentDir ? '.' : finalProjectName}. Overwrite?`),
                    initial: false,
                });
                if (!confirmOverwrite) {
                    console.log(chalk_1.default.blue("\nInitialization cancelled."));
                    return;
                }
            }
            spinner.start();
            i18nConfig = await this.askI18nConfig(options);
            if (options.specOnly) {
                await this.initBasicProject(spinner, projectPath, finalProjectName, { ...options, description: effectiveDescription }, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig);
            }
            else {
                const framework = options.framework || "nextjs";
                if (framework === "instantdb") {
                    await this.initInstantDBProject(spinner, workingDir, projectPath, finalProjectName, { ...options, description: effectiveDescription }, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig);
                }
                else if (framework === "landing") {
                    await this.initLandingPageProject(spinner, workingDir, projectPath, finalProjectName, { ...options, description: effectiveDescription }, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig);
                }
                else {
                    await this.initNextJSProject(spinner, workingDir, projectPath, finalProjectName, { ...options, description: effectiveDescription }, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig);
                }
            }
            // Generate initial premium landing page immediately
            spinner.updateText("Generating premium landing page...");
            const { DeterministicScaffoldGenerator } = await Promise.resolve().then(() => __importStar(require("../generator/scaffold")));
            const scaffolder = new DeterministicScaffoldGenerator(projectPath);
            await scaffolder.generateRootLandingPage([]);
        }
        catch (error) {
            spinner.error({ text: "Failed to initialize project" });
            if (error instanceof Error && error.message.includes("Command failed")) {
                console.log(chalk_1.default.red("\n❌ Scaffolding Failed: create-next-app cannot run in a non-empty directory."));
                console.log(chalk_1.default.blue("💡 Fix: Provide a unique project name to create a subdirectory:"));
                console.log(chalk_1.default.cyan("   mycontext init <my-project-name>\n"));
            }
            else {
                console.error(chalk_1.default.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
            }
            throw error;
        }
    }
    /**
     * Initialize an InstantDB project with full setup
     */
    async initInstantDBProject(spinner, workingDir, projectPath, projectName, options, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig) {
        // 0. Bootstrap Next.js project first
        const hasPackageJson = await fs.pathExists(path.join(projectPath, "package.json"));
        if (!hasPackageJson) {
            spinner.updateText("Bootstrapping Next.js project...");
            const projectNameParam = useCurrentDir ? "." : projectName;
            (0, child_process_1.execSync)(`npx -y create-next-app@latest ${projectNameParam} --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --use-pnpm --skip-install --no-react-compiler --no-git`, {
                cwd: workingDir,
                stdio: "inherit",
            });
            // Install initial dependencies
            spinner.updateText("Installing dependencies...");
            (0, child_process_1.execSync)("pnpm install", { cwd: projectPath, stdio: "ignore" });
        }
        // 1. Run shadcn init if components.json doesn't exist
        const componentsJsonPath = path.join(projectPath, "components.json");
        if (!fs.existsSync(componentsJsonPath)) {
            spinner.updateText("Running shadcn init...");
            const presetId = await this.getPresetId(projectPath, options);
            if (presetId) {
                console.log(chalk_1.default.blue(`🎨 Initializing shadcn/ui with preset: ${presetId}`));
                (0, child_process_1.execSync)(`pnpm dlx shadcn@latest init --preset ${presetId} --template next`, {
                    cwd: projectPath,
                    stdio: "inherit",
                });
            }
            else {
                (0, child_process_1.execSync)(`pnpm dlx shadcn@latest init ${options.yes ? "-d -y" : ""}`, {
                    cwd: projectPath,
                    stdio: "inherit",
                });
            }
        }
        else {
            console.log(chalk_1.default.blue("ℹ️  shadcn/ui already initialized, skipping..."));
        }
        // 2. Prompt user for instant-cli init
        spinner.stop();
        let runInstantInit = true;
        if (!options.yes) {
            const response = await (0, prompts_1.default)({
                type: "confirm",
                name: "runInstantInit",
                message: "Run 'npx instant-cli init' to initialize InstantDB?",
                initial: true,
            });
            runInstantInit = response.runInstantInit;
        }
        if (runInstantInit) {
            spinner.start();
            spinner.updateText("Running instant-cli init...");
            (0, child_process_1.execSync)("npx instant-cli init", {
                cwd: projectPath,
                stdio: "inherit",
            });
            // Prompt user to push schemas
            spinner.stop();
            let pushSchemas = false;
            if (!options.yes) {
                const response = await (0, prompts_1.default)({
                    type: "confirm",
                    name: "pushSchemas",
                    message: "Push schemas to InstantDB dashboard? (Make sure you've configured your app)",
                    initial: false,
                });
                pushSchemas = response.pushSchemas;
            }
            if (pushSchemas) {
                spinner.start();
                spinner.updateText("Pushing schemas to InstantDB...");
                (0, child_process_1.execSync)("npx instant-cli push", {
                    cwd: projectPath,
                    stdio: "inherit",
                });
            }
        }
        // 3. Install @instantdb/react and @instantdb/admin
        spinner.start();
        spinner.updateText("Installing InstantDB packages...");
        (0, child_process_1.execSync)("pnpm add @instantdb/react @instantdb/admin", {
            cwd: projectPath,
            stdio: "inherit",
        });
        // Install bcrypt for auth utilities
        spinner.updateText("Installing auth dependencies...");
        (0, child_process_1.execSync)("pnpm add bcryptjs nanoid && pnpm add -D @types/bcryptjs", {
            cwd: projectPath,
            stdio: "inherit",
        });
        // 4. Copy InstantDB templates to lib folder
        spinner.updateText("Copying InstantDB template files...");
        await this.fs.copyInstantDBTemplates(projectPath);
        // 5. Initialize MyContext directory structure and context
        spinner.updateText("Initializing MyContext project files...");
        const config = await this.fs.initializeProject(projectName, options.description || `${projectName} - AI-powered app`, workingDir, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig);
        await this.createInitialManifest(projectPath, projectName, options.description || `${projectName} - AI-powered app`);
        spinner.success({
            text: `Project "${projectName}" initialized successfully with InstantDB!`,
        });
        // Post-initialization environment setup
        await this.setupEnvironmentKeys(projectPath, options, "instantdb");
        // Show next steps
        this.showNextSteps(config, "instantdb", useCurrentDir);
    }
    async initNextJSProject(spinner, workingDir, projectPath, projectName, options, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig) {
        // 1. Check for Next.js presence, bootstrap if missing
        const hasPackageJson = await fs.pathExists(path.join(projectPath, "package.json"));
        if (!hasPackageJson) {
            spinner.updateText("Bootstrapping Next.js project...");
            const projectNameParam = useCurrentDir ? "." : projectName;
            // Using --yes and specific version to match user's environment
            (0, child_process_1.execSync)(`npx -y create-next-app@latest ${projectNameParam} --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --use-pnpm --skip-install --no-react-compiler --no-git`, {
                cwd: workingDir,
                stdio: "inherit",
            });
            // Install dependencies silently
            spinner.updateText("Installing dependencies...");
            (0, child_process_1.execSync)("pnpm install", { cwd: projectPath, stdio: "ignore" });
        }
        // 2. Run shadcn init if components.json doesn't exist
        const componentsJsonPath = path.join(projectPath, "components.json");
        if (!fs.existsSync(componentsJsonPath)) {
            spinner.updateText("Running shadcn init...");
            const presetId = await this.getPresetId(projectPath, options);
            if (presetId) {
                console.log(chalk_1.default.blue(`🎨 Initializing shadcn/ui with preset: ${presetId}`));
                (0, child_process_1.execSync)(`pnpm dlx shadcn@latest init --preset ${presetId} --template next`, {
                    cwd: projectPath,
                    stdio: "inherit",
                });
            }
            else {
                // -d for defaults, -y for non-interactive
                (0, child_process_1.execSync)("pnpm dlx shadcn@latest init -d -y", {
                    cwd: projectPath,
                    stdio: "inherit",
                });
            }
        }
        else {
            console.log(chalk_1.default.blue("ℹ️  shadcn/ui already initialized, skipping..."));
        }
        // 2. Initialize MyContext directory structure and context
        spinner.updateText("Initializing MyContext project files...");
        const config = await this.fs.initializeProject(projectName, options.description || `${projectName} - Next.js app`, workingDir, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig);
        await this.createInitialManifest(projectPath, projectName, options.description || `${projectName} - Next.js app`);
        spinner.success({
            text: `Project "${projectName}" initialized successfully with Next.js!`,
        });
        // Post-initialization environment setup
        await this.setupEnvironmentKeys(projectPath, options, "nextjs");
        // Show next steps
        this.showNextSteps(config, "nextjs", useCurrentDir);
    }
    async initLandingPageProject(spinner, workingDir, projectPath, projectName, options, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig) {
        // 1. Standard Next.js bootstrap
        await this.initNextJSProject(spinner, workingDir, projectPath, projectName, options, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig);
        // 2. Specialized Landing Page scaffolding
        spinner.updateText("Generating specialized landing page architecture...");
        const { DeterministicScaffoldGenerator } = await Promise.resolve().then(() => __importStar(require("../generator/scaffold")));
        const scaffolder = new DeterministicScaffoldGenerator(projectPath);
        // We update the context to reflect it's a landing-page project
        const contextPath = path.join(projectPath, ".mycontext", "context.json");
        if (fs.existsSync(contextPath)) {
            const context = await fs.readJson(contextPath);
            context.projectType = "landing-page";
            context.aestheticPreference = "premium-high-fidelity";
            await fs.writeJson(contextPath, context, { spaces: 2 });
        }
        await scaffolder.generateRootLandingPage([]);
        spinner.success({
            text: `Premium Landing Page project "${projectName}" ready for ideation!`,
        });
        console.log(chalk_1.default.cyan("\n🚀 Tip: Run 'mycontext ideate' to generate UI concepts for your landing page.\n"));
    }
    /**
     * Initialize a basic MyContext project (no framework)
     */
    async initBasicProject(spinner, projectPath, projectName, options, useCurrentDir, selectedScopes, ignorePatterns, i18nConfig) {
        spinner.updateText("Initializing MyContext project files...");
        const config = await this.fs.initializeProject(projectName, options.description || `${projectName} - AI-powered app`, process.cwd(), useCurrentDir, selectedScopes, ignorePatterns, i18nConfig);
        await this.createInitialManifest(projectPath, projectName, options.description || `${projectName} - AI-powered app`);
        spinner.success({
            text: `Project "${projectName}" initialized successfully!`,
        });
        // Post-initialization environment setup
        await this.setupEnvironmentKeys(projectPath, options, undefined);
        // Show next steps
        this.showNextSteps(config, undefined, useCurrentDir);
    }
    isValidProjectName(name) {
        // Allow alphanumeric, hyphens, and underscores
        return /^[a-zA-Z0-9._-]+$/.test(name);
    }
    async setupEnvironmentKeys(projectPath, options, framework) {
        const envPath = path.join(projectPath, ".env.local");
        const hasEnv = await fs.pathExists(envPath);
        let envContent = hasEnv ? await fs.readFile(envPath, "utf-8") : "";
        console.log(chalk_1.default.blue("\n🔑 Environment Configuration:"));
        if (options.yes) {
            console.log(chalk_1.default.gray("ℹ️  Non-interactive mode: Skipping environment prompts."));
            return;
        }
        const keysToPrompt = [];
        // Always prompt for GitHub Token (Preferred for reliability right now)
        if (!process.env.GITHUB_TOKEN && !envContent.includes("GITHUB_TOKEN")) {
            keysToPrompt.push({
                type: "password",
                name: "githubToken",
                message: "Enter your GitHub Classic Token (with 'repo' scopes for AI Models):",
            });
        }
        // Still allow Gemini API Key but mark as optional/secondary
        if (!process.env.GEMINI_API_KEY && !envContent.includes("GEMINI_API_KEY")) {
            keysToPrompt.push({
                type: "password",
                name: "geminiKey",
                message: "Enter your Gemini API Key (Optional, get it from aistudio.google.com):",
            });
        }
        // Prompt for InstantDB App ID if using instantdb and not present
        if (framework === "instantdb" && !envContent.includes("NEXT_PUBLIC_INSTANT_APP_ID")) {
            keysToPrompt.push({
                type: "input",
                name: "instantAppId",
                message: "Enter your InstantDB App ID:",
            });
        }
        if (keysToPrompt.length > 0) {
            const answers = await inquirer_1.default.prompt(keysToPrompt);
            let newVars = "";
            if (answers.githubToken) {
                newVars += `\nGITHUB_TOKEN=${answers.githubToken}`;
            }
            if (answers.geminiKey) {
                newVars += `\nGEMINI_API_KEY=${answers.geminiKey}`;
            }
            if (answers.instantAppId) {
                newVars += `\nNEXT_PUBLIC_INSTANT_APP_ID=${answers.instantAppId}`;
            }
            if (newVars) {
                if (!envContent) {
                    envContent = "# MyContext Environment Variables" + newVars;
                }
                else {
                    envContent += newVars;
                }
                await fs.writeFile(envPath, envContent);
                console.log(chalk_1.default.green("✅ Environment variables saved to .env.local"));
            }
        }
        else {
            console.log(chalk_1.default.gray("ℹ️  Required environment variables are already set."));
        }
    }
    showNextSteps(config, framework, useCurrentDir) {
        const projectPath = useCurrentDir ? "./" : config.name;
        console.log(chalk_1.default.blue("\n🎯 Next Steps:\n"));
        let step = 1;
        if (!useCurrentDir) {
            console.log(chalk_1.default.yellow(`  ${step++}. cd ` + projectPath));
        }
        console.log(chalk_1.default.yellow(`  ${step++}. Generate Full Context (FSR + Component Discovery):`));
        console.log(chalk_1.default.cyan(`      mycontext generate context --full\n`));
        console.log(chalk_1.default.yellow(`  ${step++}. Command Chain (Context -> Design Prompt):`));
        console.log(chalk_1.default.cyan(`      mycontext generate context --full && mycontext gdp\n`));
        console.log(chalk_1.default.yellow(`  ${step++}. Sync & Update Brain (as needed):`));
        console.log(chalk_1.default.cyan("      mycontext sync\n"));
        console.log(chalk_1.default.green("✨ MyContext v4.2.17 | Context-Driven Development Activated\n"));
        console.log(chalk_1.default.green("✨ Tips:"));
        console.log(chalk_1.default.gray("• Check .mycontext/ for all generated files"));
        if (framework === "instantdb") {
            console.log(chalk_1.default.gray("• InstantDB templates are ready to use in your lib/ folder"));
            console.log(chalk_1.default.gray("• Update instant.schema.ts with your data model"));
        }
        console.log(chalk_1.default.gray("• Use --yes flag to skip prompts"));
        console.log(chalk_1.default.gray("• Run 'mycontext status' to check project progress\n"));
    }
    /**
     * Create the initial design manifest as a Hard Gravity anchor
     */
    async createInitialManifest(projectPath, projectName, description) {
        const manager = new core_1.DesignManifestManager(projectPath);
        const manifest = manager.createDefaultManifest(projectName, description);
        await manager.saveDesignManifest(manifest);
    }
    async askI18nConfig(options) {
        if (options.yes)
            return undefined;
        const { enableI18n } = await (0, prompts_1.default)({
            type: "confirm",
            name: "enableI18n",
            message: "🌍 Enable Internationalization (i18n) Context Layer?",
            initial: true
        });
        if (!enableI18n)
            return undefined;
        const { defaultLocale, locales, dictionaryPath } = await (0, prompts_1.default)([
            {
                type: "text",
                name: "defaultLocale",
                message: "Default locale:",
                initial: "en"
            },
            {
                type: "text",
                name: "locales",
                message: "Supported locales (comma-separated):",
                initial: "en,sw,fr"
            },
            {
                type: "text",
                name: "dictionaryPath",
                message: "Dictionary path:",
                initial: "dictionaries"
            }
        ]);
        return {
            defaultLocale,
            locales: locales ? locales.split(",").map((l) => l.trim()) : ["en"],
            dictionaryPath
        };
    }
    async getPresetId(projectPath, options) {
        let presetId = options.preset;
        if (!presetId && options.presetAgent) {
            try {
                const { ShadcnPresetAgent } = await Promise.resolve().then(() => __importStar(require("../services/ShadcnPresetAgent")));
                const agent = new ShadcnPresetAgent({ projectRoot: projectPath, verbose: true });
                presetId = await agent.generatePreset();
            }
            catch (err) {
                console.log(chalk_1.default.yellow(`⚠️  Failed to generate preset: ${err.message}. Falling back to default.`));
            }
        }
        return presetId;
    }
    displayBranding() {
        try {
            const logo = figlet_1.default.textSync("MyContext", {
                font: "Standard",
                horizontalLayout: "default",
                verticalLayout: "default",
            });
            // Apply gradient to the logo
            console.log(gradient_string_1.default.pastel.multiline(logo));
            console.log(chalk_1.default.cyan.bold("    🧠 Living Brain | Context-Driven Development (v4.2.17)\n"));
        }
        catch (error) {
            // Fallback to simple text if figlet fails
            console.log(chalk_1.default.blue.bold("\n🧠 MyContext - Context-Driven Development\n"));
        }
    }
}
exports.InitCommand = InitCommand;
//# sourceMappingURL=init.js.map