// packages/plugin-awf/src/utils/vscode-settings.ts
// v6.4.12: VS Code settings injection for Copilot integration
//
// Injects settings like `chat.promptFilesLocations` so Copilot
// auto-discovers AWF workflows without needing to copy/transform them.
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
import { join } from "node:path";
/**
 * Merge settings into .vscode/settings.json without overwriting existing values.
 * Creates .vscode/ directory and settings.json if they don't exist.
 *
 * @returns true if settings were written, false if no changes needed
 */
export function injectVSCodeSettings(rootDir, newSettings) {
    const vscodeDir = join(rootDir, ".vscode");
    const settingsPath = join(vscodeDir, "settings.json");
    // Read existing settings (or empty object)
    let existing = {};
    if (existsSync(settingsPath)) {
        try {
            const raw = readFileSync(settingsPath, "utf-8");
            // Strip BOM and trailing commas before parsing
            const cleaned = raw
                .replace(/^\uFEFF/, "")
                .replace(/,\s*([\]}])/g, "$1");
            existing = JSON.parse(cleaned);
        }
        catch {
            // If parse fails, preserve file as-is — don't overwrite
            return false;
        }
    }
    // Deep merge: only add keys that don't already exist
    let changed = false;
    for (const [key, value] of Object.entries(newSettings)) {
        if (!(key in existing)) {
            existing[key] = value;
            changed = true;
        }
        else if (typeof value === "object" &&
            value !== null &&
            !Array.isArray(value) &&
            typeof existing[key] === "object" &&
            existing[key] !== null) {
            // Deep merge for object values (e.g., chat.promptFilesLocations)
            const existingObj = existing[key];
            for (const [subKey, subValue] of Object.entries(value)) {
                if (!(subKey in existingObj)) {
                    existingObj[subKey] = subValue;
                    changed = true;
                }
            }
        }
    }
    if (!changed)
        return false;
    // Write back with 2-space indent
    mkdirSync(vscodeDir, { recursive: true });
    writeFileSync(settingsPath, JSON.stringify(existing, null, 2) + "\n", "utf-8");
    return true;
}
/**
 * Default VS Code settings for AWF Copilot integration.
 * Adds .agent/workflows as a prompt file search location.
 */
export const AWF_VSCODE_SETTINGS = {
    "chat.promptFilesLocations": {
        ".agent/workflows": true,
    },
};
