// packages/plugin-awf/src/commands/install-core.ts
// Core AWF installation logic, extracted from install.ts
// v4: Tiered install profiles + MCP-aware copy optimization
import * as fs from "node:fs";
import { emptyCopyResult } from "../types/ide-install.js";
import { getInstallSpec } from "../constants/ide-install-specs.js";
import { copySkills, copyWorkflows, copyRules, copyCore, initMemory, copyPersonas, copyTemplates, copyRootConfig, copyAgents, copyHooks, } from "../utils/copy-helpers.js";
import { validateInstallation } from "../utils/validation.js";
import { resolveGlobalTargets, resolveLanguage } from "./install-helpers.js";
import { copyHSA } from "./install-hsa.js";
import { writeManifest } from "../utils/install-manifest.js";
import { PROFILES } from "./install.js";
import { injectVSCodeSettings, AWF_VSCODE_SETTINGS } from "../utils/vscode-settings.js";
import pc from "picocolors";
// ══════════════════════════════════════════════════════════════
// Core Install Function (v4: Tiered Profiles + MCP-Aware)
// ══════════════════════════════════════════════════════════════
export async function installAWF(ide, scope, rootDir, sourceDir, configsDir, force, dryRun, langFlag, profile = "standard", mcpSupported = false) {
    const baseSpec = getInstallSpec(ide.value);
    const profileConfig = PROFILES[profile];
    // Deep Audit v4: Resolve globalTarget overrides for global scope
    // Some IDEs (e.g., Antigravity) need different target paths for global vs project
    const spec = scope === "global" ? resolveGlobalTargets(baseSpec) : baseSpec;
    // v4 Tier 2: Determine whether to skip MCP-redundant files
    // tier2=false (minimal): always skip tier2
    // tier2="mcp-conditional" (standard): skip if MCP supported
    // tier2=true (full): always copy everything
    const skipTier2 = profileConfig.tier2 === false
        || (profileConfig.tier2 === "mcp-conditional" && mcpSupported);
    const results = {
        ide: ide.value,
        scope,
        skills: emptyCopyResult(),
        workflows: emptyCopyResult(),
        rules: emptyCopyResult(),
        core: emptyCopyResult(),
        memory: emptyCopyResult(),
        personas: emptyCopyResult(),
        templates: emptyCopyResult(),
        hsa: emptyCopyResult(),
        rootConfig: false,
    };
    // Check if source exists
    if (!sourceDir) {
        if (!dryRun) {
            console.log(pc.yellow(`  ⚠ AWF source not found for ${ide.value}. Ensure @nockdev/awf is installed:`));
            console.log(pc.dim(`    npm install -g @nockdev/cli && nock plugins install @nockdev/awf`));
        }
        return results;
    }
    if (dryRun) {
        console.log(pc.dim(`  [${scope}] Would install to: ${rootDir} (profile: ${profile}, mcp: ${mcpSupported}, skipTier2: ${skipTier2})`));
        return results;
    }
    // Ensure root directory exists
    fs.mkdirSync(rootDir, { recursive: true });
    const tag = pc.dim(`  [${ide.value}/${scope}]`);
    // 1. Copy Skills (Tier 1: profile controls count)
    if (spec.skills.enabled) {
        results.skills = copySkills(spec.skills, rootDir, sourceDir);
        if (results.skills.count > 0)
            console.log(`${tag} ${pc.green("✔")} Skills (${results.skills.count})`);
    }
    // 2. Copy Workflows (Tier 1: with i18n)
    if (spec.workflows.enabled) {
        const lang = resolveLanguage(langFlag, rootDir);
        spec.workflows.language = lang;
        results.workflows = copyWorkflows(spec.workflows, rootDir, sourceDir);
        if (results.workflows.count > 0)
            console.log(`${tag} ${pc.green("✔")} Workflows (${results.workflows.count})`);
    }
    // 3. Copy Rules (Tier 0 + Tier 1 + conditionally Tier 2)
    //    SACRED_RULES.xml is ALWAYS copied (Tier 0)
    //    Modules are profile-dependent (Tier 1)
    //    Standalones + data/ are skipped when skipTier2=true (Tier 2)
    if (spec.rules.enabled) {
        const moduleWhitelist = typeof profileConfig.modules === "string"
            ? profileConfig.modules // "all"
            : profileConfig.modules; // string[]
        results.rules = copyRules(spec.rules, rootDir, sourceDir, {
            mcpSupported: skipTier2,
            moduleWhitelist,
        });
        if (results.rules.count > 0)
            console.log(`${tag} ${pc.green("✔")} Rules (${results.rules.count})`);
    }
    // 4. Copy Core Engine Files — Tier 2 (skip for MCP IDEs)
    if (spec.core.enabled && !skipTier2) {
        results.core = copyCore(spec.core, rootDir, sourceDir);
        if (results.core.count > 0)
            console.log(`${tag} ${pc.green("✔")} Core (${results.core.count})`);
    }
    // 5. Initialize Memory Structure (Tier 1 — always useful)
    if (spec.memory.enabled) {
        results.memory = initMemory(spec.memory, rootDir, langFlag);
        if (results.memory.count > 0)
            console.log(`${tag} ${pc.green("✔")} Memory`);
    }
    // 6. Copy Personas — Tier 2 (skip for MCP IDEs)
    if (spec.personas.enabled && !skipTier2) {
        results.personas = copyPersonas(spec.personas, rootDir, sourceDir);
        if (results.personas.count > 0)
            console.log(`${tag} ${pc.green("✔")} Personas (${results.personas.count})`);
    }
    // 7. Copy Templates (Tier 1 — always useful)
    if (spec.templates.enabled) {
        results.templates = copyTemplates(spec.templates, rootDir, sourceDir);
        if (results.templates.count > 0)
            console.log(`${tag} ${pc.green("✔")} Templates (${results.templates.count})`);
    }
    // 8. Copy Root Config (Tier 0 — IDE-specific, always needed)
    //    v6.3.0: Inject language instruction into rootConfig template
    if (spec.rootConfig.source && configsDir) {
        const lang = resolveLanguage(langFlag, rootDir);
        results.rootConfig = copyRootConfig(spec.rootConfig, rootDir, configsDir, lang);
    }
    // 9. Copy Custom Agents (VS Code: .github/agents/*.agent.md)
    if (spec.agents?.enabled && configsDir) {
        results.agents = copyAgents(spec.agents, rootDir, configsDir);
        if (results.agents.count > 0)
            console.log(`${tag} ${pc.green("✔")} Agents (${results.agents.count})`);
    }
    // 10. Copy Hooks (VS Code: .github/hooks/hooks.json)
    if (spec.hooks?.enabled && configsDir) {
        results.hooks = copyHooks(spec.hooks, rootDir, configsDir);
        if (results.hooks.count > 0)
            console.log(`${tag} ${pc.green("✔")} Hooks (${results.hooks.count})`);
    }
    // 10b. Inject VS Code settings (project scope only)
    // Adds chat.promptFilesLocations so Copilot also discovers .agent/workflows/
    if (ide.value === "vscode" && scope === "project") {
        const injected = injectVSCodeSettings(rootDir, AWF_VSCODE_SETTINGS);
        if (injected)
            console.log(`${tag} ${pc.green("✔")} VS Code settings (chat.promptFilesLocations)`);
    }
    // 11. Copy HSA (npx-based, no actual file copy) — project scope only
    if (scope === "project" && sourceDir) {
        results.hsa = copyHSA(rootDir, sourceDir);
    }
    // 10. Validate installation
    results.validation = validateInstallation(spec, rootDir, results);
    // 11. Write install manifest (for debugging/auditing)
    if (scope === "project") {
        writeManifest(rootDir, {
            ide: ide.value,
            profile,
            mcpSupported,
            skipTier2,
            language: langFlag || resolveLanguage(undefined, rootDir),
        });
    }
    return results;
}
