"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.cliRules = void 0;
const path = __importStar(require("path"));
const REQUIRED_CONTEXT_KEYS = ["prd", "features", "specs", "metadata", "brain"];
function missingContextKeys(context) {
    if (!context || typeof context !== "object")
        return [...REQUIRED_CONTEXT_KEYS];
    return REQUIRED_CONTEXT_KEYS.filter((k) => !(k in context));
}
const cliVersion = {
    id: "cli/version",
    name: "CLI Version Compatibility",
    category: "node",
    severity: "warning",
    description: "Check if the CLI version is compatible with the project setup",
    help: "Run 'npm install -g @myycontext/cli@latest' to update your CLI",
    appliesTo: ["node", "nextjs", "turbo"],
    async check(ctx) {
        const results = [];
        const pkg = await ctx.readJson("package.json");
        // In a real scenario, we'd compare against a minimum required version
        // For now, we'll just check if the CLI itself is a reasonable version
        return results;
    },
};
const configHealth = {
    id: "mycontext/config-health",
    name: "MyContext Config Health",
    category: "node",
    severity: "error",
    description: "Verify that MyContext configuration files are present and valid",
    help: "Run 'mycontext init' to repair your project configuration",
    appliesTo: ["node", "nextjs", "turbo"],
    async check(ctx) {
        const results = [];
        if (!(await ctx.fileExists(".mycontext/config.json"))) {
            results.push({
                ruleId: this.id,
                filePath: ".mycontext/config.json",
                severity: "error",
                message: "Missing config.json in .mycontext directory",
                help: "Run 'mycontext init' to re-initialize your project",
                autoFixable: true
            });
        }
        if (!(await ctx.fileExists(".mycontext/context.json"))) {
            results.push({
                ruleId: this.id,
                filePath: ".mycontext/context.json",
                severity: "error",
                message: "Missing context.json (Living Brain) in .mycontext directory",
                help: "Run 'mycontext sync' or 'mycontext generate context' to build your brain",
                autoFixable: true
            });
        }
        else {
            const context = await ctx.readJson(".mycontext/context.json");
            const missing = missingContextKeys(context);
            if (missing.length > 0) {
                results.push({
                    ruleId: this.id,
                    filePath: ".mycontext/context.json",
                    severity: "error",
                    message: `Incomplete context.json: missing ${missing.join(", ")}`,
                    help: `Expected required keys: ${REQUIRED_CONTEXT_KEYS.join(", ")}. Minimal valid shape: {"prd":{},"features":[],"specs":{},"metadata":{"version":"1.0.0"},"brain":{"version":"1.0.0"}}`,
                    autoFixable: true
                });
            }
        }
        return results;
    },
    async fix(ctx, diag) {
        if (diag.filePath === ".mycontext/config.json") {
            const defaultConfig = {
                version: "1.0.0",
                project: ctx.project.name,
                lastUpdated: new Date().toISOString()
            };
            return await ctx.writeFile(".mycontext/config.json", JSON.stringify(defaultConfig, null, 2));
        }
        if (diag.filePath === ".mycontext/context.json") {
            const defaultContext = {
                prd: { title: ctx.project.name },
                features: [],
                specs: {},
                metadata: { version: "1.0.0", generatedAt: new Date().toISOString() },
                brain: { version: "1.0.0", status: "initialized" }
            };
            // If it exists but is incomplete, merge with existing
            if (await ctx.fileExists(".mycontext/context.json")) {
                const existing = await ctx.readJson(".mycontext/context.json") || {};
                const merged = { ...defaultContext, ...existing };
                return await ctx.writeFile(".mycontext/context.json", JSON.stringify(merged, null, 2));
            }
            return await ctx.writeFile(".mycontext/context.json", JSON.stringify(defaultContext, null, 2));
        }
        return false;
    },
};
const legacyMarkdownCleanup = {
    id: "cli/legacy-markdown-cleanup",
    name: "Legacy Markdown Cleanup",
    category: "node",
    severity: "warning",
    description: "Detect redundant fragmented Markdown files from previous context generation",
    help: "Run 'mycontext doctor --fix' to remove these redundant files and use the consolidated views instead",
    appliesTo: ["node", "nextjs", "turbo"],
    async check(ctx) {
        const results = [];
        const legacyFiles = [
            ".mycontext/01a-features.md",
            ".mycontext/01b-user-flows.md",
            ".mycontext/01c-edge-cases.md",
            ".mycontext/01d-technical-specs.md",
            ".mycontext/02-types-guide.md",
            ".mycontext/04-component-list.md",
            ".mycontext/01a-brief.md",
            ".mycontext/01b-requirements.md",
            ".mycontext/01c-flows.md",
        ];
        for (const file of legacyFiles) {
            if (await ctx.fileExists(file)) {
                results.push({
                    ruleId: this.id,
                    filePath: file,
                    severity: "warning",
                    message: `Redundant fragmented Markdown file detected: ${path.basename(file)}`,
                    help: "These files have been consolidated into unified views. You can safely remove them.",
                    autoFixable: true
                });
            }
        }
        return results;
    },
    async fix(ctx, diag) {
        return await ctx.deleteFile(diag.filePath);
    }
};
const aiProviderEnv = {
    id: "security/ai-provider-env",
    name: "AI Provider Configuration",
    category: "security",
    severity: "error",
    description: "Verify that at least one AI provider API key is configured",
    help: "Add MYCONTEXT_OPENROUTER_API_KEY to your .mycontext/.env or your system environment",
    appliesTo: ["node", "nextjs", "turbo"],
    async check(ctx) {
        const results = [];
        // Check for common keys in process.env or .mycontext/.env
        const envFile = await ctx.readFile(".mycontext/.env").catch(() => null);
        const hasInEnv = envFile && (envFile.includes("MYCONTEXT_OPENROUTER_API_KEY") ||
            envFile.includes("OPENROUTER_API_KEY") ||
            envFile.includes("ANTHROPIC_API_KEY") ||
            envFile.includes("OPENAI_API_KEY") ||
            envFile.includes("XAI_API_KEY") ||
            envFile.includes("GEMINI_API_KEY"));
        const hasInProcess = (process.env.MYCONTEXT_OPENROUTER_API_KEY ||
            process.env.OPENROUTER_API_KEY ||
            process.env.ANTHROPIC_API_KEY ||
            process.env.OPENAI_API_KEY ||
            process.env.XAI_API_KEY ||
            process.env.GEMINI_API_KEY);
        if (!hasInEnv && !hasInProcess) {
            results.push({
                ruleId: this.id,
                filePath: ".mycontext/.env",
                severity: "error",
                message: "No AI provider API keys detected",
                help: "Context generation requires an AI backend. Please configure an API key (e.g., OpenRouter).",
                autoFixable: false
            });
        }
        return results;
    }
};
exports.cliRules = [
    cliVersion,
    configHealth,
    legacyMarkdownCleanup,
    aiProviderEnv
];
//# sourceMappingURL=cli-rules.js.map