// packages/plugin-awf/src/commands/init.ts
// AWF Init Command - Initialize DOMYH in project
// v1.1.0: UX improvements — tiered IDE list, scope selector, multi-detect
import * as fs from "node:fs";
import * as path from "node:path";
import pc from "picocolors";
import * as prompts from "@clack/prompts";
import { AWF_VERSION } from "../constants.js";
import { showBanner } from "../utils/branding.js";
import { getIDEOptionsWithTiers, resolveIDESelection, IDE_REGISTRY, } from "../constants/ides.js";
export const initFlags = {
    force: {
        type: "boolean",
        description: "Overwrite existing .agent directory without prompting",
        alias: "f",
        default: false,
    },
    language: {
        type: "string",
        description: "Set language (en/vi)",
        alias: "l",
        choices: ["en", "vi"],
    },
    agent: {
        type: "string",
        description: "Target AI agent (cursor, windsurf, gemini, claude, etc.)",
        alias: "a",
    },
    skills: {
        type: "string",
        description: "Initial skills to install (comma-separated)",
        alias: "s",
    },
    yes: {
        type: "boolean",
        description: "Accept all defaults",
        alias: "y",
        default: false,
    },
};
export async function initCommand(args, flags) {
    const cwd = process.cwd();
    const agentDir = path.join(cwd, ".agent");
    // BUG-FIX #3 (P1): Support --force flag to skip overwrite prompt
    const force = flags.force || flags.yes;
    // A-01/A-03: Auto mode — skip ALL prompts when --yes or CI environment
    const isCI = !!(process.env.CI || process.env.CONTINUOUS_INTEGRATION
        || process.env.GITHUB_ACTIONS || process.env.GITLAB_CI);
    const autoMode = flags.yes || isCI;
    // BRAND-04: NOCK gradient branded banner
    await showBanner(AWF_VERSION, "Project Initialization");
    // Step 1: Language selection
    console.log(pc.dim("  [1/4]") + " Language");
    let language;
    if (flags.language && ["en", "vi"].includes(flags.language)) {
        language = flags.language;
    }
    else if (autoMode) {
        language = "vi";
        console.log(pc.dim("  Language: vi (auto)"));
    }
    else {
        const langSelection = await prompts.select({
            message: "Select language / Chọn ngôn ngữ",
            options: [
                { value: "en", label: "English" },
                { value: "vi", label: "Tiếng Việt" },
            ],
        });
        if (prompts.isCancel(langSelection)) {
            prompts.outro(pc.yellow("Cancelled"));
            return;
        }
        language = langSelection;
    }
    // SYNC-02: Save language to state.json for subsequent commands
    try {
        const memoryDir = path.join(cwd, ".agent", "memory");
        if (fs.existsSync(path.join(cwd, ".agent"))) {
            if (!fs.existsSync(memoryDir)) {
                fs.mkdirSync(memoryDir, { recursive: true });
            }
            const stateFile = path.join(memoryDir, "state.json");
            const state = fs.existsSync(stateFile)
                ? JSON.parse(fs.readFileSync(stateFile, "utf-8"))
                : {};
            state.preferences = { ...state.preferences, language };
            fs.writeFileSync(stateFile, JSON.stringify(state, null, 2));
        }
    }
    catch { /* ignore state save errors */ }
    // Step 2: Check existing .agent directory
    console.log(pc.dim("  [2/4]") + " Check project");
    if (fs.existsSync(agentDir)) {
        if (!force) {
            const overwrite = await prompts.confirm({
                message: ".agent directory already exists. Overwrite?",
                initialValue: false,
            });
            if (prompts.isCancel(overwrite) || !overwrite) {
                prompts.outro(pc.yellow("Cancelled"));
                return;
            }
        }
        else {
            console.log(pc.dim("  --force: overwriting existing .agent directory"));
        }
    }
    // Agent detection/selection (multiselect with tiered grouping)
    // v1.1.0: Use SSoT IDE registry + detect ALL existing IDEs
    const detectedAgents = detectAllAgents(cwd);
    let selectedAgents = [];
    if (flags.agent) {
        selectedAgents = flags.agent.split(",").map((s) => s.trim());
    }
    else if (autoMode) {
        // Auto mode: Tier 1 popular IDEs + any detected IDEs
        const popularIDEs = ["cursor", "claude", "gemini", "antigravity", "vscode", "windsurf"];
        selectedAgents = [...new Set([...detectedAgents, ...popularIDEs])];
        console.log(pc.dim(`  IDEs: ${selectedAgents.length} selected (auto)`));
    }
    else {
        // Default: Tier 1 popular IDEs + any detected IDEs
        const popularIDEs = ["cursor", "claude", "gemini", "antigravity", "vscode", "windsurf"];
        const defaultSelection = [...new Set([...detectedAgents, ...popularIDEs])];
        if (detectedAgents.length > 0) {
            console.log(pc.dim(`  Detected ${detectedAgents.length} IDE(s): ${detectedAgents.join(", ")}`));
        }
        const agents = await prompts.multiselect({
            message: "Select AI agent(s) (Tier 1 + detected pre-selected)",
            options: getIDEOptionsWithTiers(),
            required: true,
            initialValues: defaultSelection,
        });
        if (prompts.isCancel(agents)) {
            prompts.outro(pc.yellow("Cancelled"));
            return;
        }
        // Resolve tier selections (e.g., "Select All", "Tier 1") to individual IDEs
        const resolvedIDEs = resolveIDESelection(agents);
        selectedAgents = resolvedIDEs.map((ide) => ide.value);
    }
    const agent = selectedAgents[0] || "other"; // Primary agent for config
    // Skills: default to all (install copies entire skills directory)
    const skillsInput = flags.skills;
    const selectedSkills = skillsInput
        ? skillsInput.split(",").map((s) => s.trim())
        : []; // Empty = install ALL skills from SSoT
    // Create .agent structure
    const spinner = prompts.spinner();
    spinner.start("Creating .agent structure...");
    try {
        // Create directories
        const dirs = [
            ".agent",
            ".agent/core",
            ".agent/memory",
            ".agent/rules",
            ".agent/workflows",
        ];
        for (const dir of dirs) {
            const dirPath = path.join(cwd, dir);
            if (!fs.existsSync(dirPath)) {
                fs.mkdirSync(dirPath, { recursive: true });
            }
        }
        // Create/merge state.json — preserve existing user config (tokens, notifications, custom flags)
        const stateFile = path.join(cwd, ".agent/memory/state.json");
        let existingState = {};
        if (fs.existsSync(stateFile)) {
            try {
                existingState = JSON.parse(fs.readFileSync(stateFile, "utf-8"));
            }
            catch { /* ignore */ }
        }
        const state = {
            ...existingState,
            initialized: new Date().toISOString(),
            version: AWF_VERSION,
            preferences: {
                ...(existingState.preferences || {}),
                language,
                agent,
                agents: selectedAgents,
            },
            skills: selectedSkills.length > 0 ? selectedSkills : (existingState.skills || []),
        };
        fs.writeFileSync(stateFile, JSON.stringify(state, null, 2));
        // Create minimal GEMINI.md with language enforcement instruction
        const langInstruction = language === "vi"
            ? "Tiếng Việt — PHẢI trả lời TOÀN BỘ bằng tiếng Việt. Chỉ giữ tiếng Anh cho code, technical terms, commands. KHÔNG tự chuyển ngôn ngữ."
            : "English — Respond entirely in English.";
        const geminiContent = `# GEMINI.md — DOMYH Awesome Code

> 🎯 AI-powered development assistant
> 🌍 Language: ${langInstruction}
> 🤖 Agent: ${agent}

## Commands

| Command  | Description |
|----------|-------------|
| /init    | Initialize project |
| /code    | Write quality code |
| /debug   | Systematic debugging |
| /test    | Run and write tests |
| /deploy  | Deploy to production |
| /help    | Show help |

---
_DOMYH Awesome Code v${AWF_VERSION} • NockDev_
`;
        fs.writeFileSync(path.join(cwd, ".agent/GEMINI.md"), geminiContent);
        spinner.stop("Created .agent structure");
        // Summary
        console.log();
        console.log(pc.bold("Configuration:"));
        console.log(`  ${pc.dim("Language:")} ${language}`);
        console.log(`  ${pc.dim("Agent(s):")} ${selectedAgents.join(", ")}`);
        if (selectedSkills.length > 0) {
            console.log(`  ${pc.dim("Skills:")} ${selectedSkills.join(", ")} (${selectedSkills.length} total)`);
        }
        prompts.outro(pc.green("✔ DOMYH initialized successfully!"));
        // ══════════════════════════════════════════════════════════════
        // Auto-chain: Init → Install
        // Ask user if they want to install skills, workflows, MCP now
        // ══════════════════════════════════════════════════════════════
        console.log();
        // Auto mode: skip confirmation, use defaults
        const shouldAutoInstall = autoMode ? true : await (async () => {
            const result = await prompts.confirm({
                message: "Install skills, workflows, and configure MCP now?",
                initialValue: true,
            });
            return !prompts.isCancel(result) && result;
        })();
        if (shouldAutoInstall) {
            // Scope selection — auto mode defaults to "both"
            let scopeSelection;
            if (autoMode) {
                scopeSelection = "both";
                console.log(pc.dim("  Scope: both (auto)"));
            }
            else {
                const scopeResult = await prompts.select({
                    message: "Installation scope",
                    options: [
                        { value: "project", label: "📁 Project only", hint: "Current directory" },
                        { value: "global", label: "🌐 Global only", hint: "Available in all projects" },
                        { value: "both", label: "✨ Both (Recommended)", hint: "Project + Global" },
                    ],
                });
                if (prompts.isCancel(scopeResult)) {
                    prompts.outro(pc.yellow("Cancelled"));
                    return;
                }
                scopeSelection = scopeResult;
            }
            // Chain to install with init selections pre-filled
            // Bug #10 fix: install for ALL selected agents, not just the first
            const { installCommand } = await import("./install.js");
            await installCommand([], {
                ide: selectedAgents.join(","), // All selected IDEs (comma-separated)
                scope: scopeSelection, // User-selected or auto scope
                profile: "standard", // Default profile
                language, // Language selected in init
                force: true, // Always force when chained from init (user already confirmed)
                validate: true,
            });
        }
        else {
            // Show manual next steps
            console.log();
            console.log(pc.dim("Next steps:"));
            console.log(`  ${pc.cyan("nock awf install")} to install skills, workflows + configure MCP`);
            console.log(`  ${pc.cyan("nock awf add <skill>")} to add more skills`);
            console.log(`  ${pc.cyan("nock awf list")} to see available skills`);
            console.log(`  ${pc.cyan("nock awf hsa start")} to start HSA MCP server`);
        }
    }
    catch (error) {
        spinner.stop(pc.red("Failed to create .agent structure"));
        console.error(error);
    }
}
/**
 * Detect ALL existing IDE configurations in the project directory.
 * v1.2.0: Uses IDE_REGISTRY (SSoT) instead of duplicated indicators.
 */
export function detectAllAgents(cwd) {
    return IDE_REGISTRY.filter(ide => {
        // Check rulePath (primary indicator)
        if (fs.existsSync(path.join(cwd, ide.rulePath)))
            return true;
        // Check configFile (e.g., .cursorrules, .windsurfrules)
        if (ide.configFile && fs.existsSync(path.join(cwd, ide.configFile)))
            return true;
        // Check rootConfigFile (e.g., GEMINI.md, CLAUDE.md)
        if (ide.rootConfigFile && fs.existsSync(path.join(cwd, ide.rootConfigFile)))
            return true;
        return false;
    }).map(ide => ide.value);
}
