// tools/create-rule.ts — SPEC-779: create_rule MCP tool
// Creates a host-aware rule file for any Planu-using project.
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { detectHost } from '../engine/host-detection/detect-host.js';
import { writeRuleForHost } from '../engine/universal-rules/host-writer.js';
import { hashContent } from '../engine/universal-rules/user-edit-detector.js';
import { hashProjectPath } from '../storage/base-store.js';
import { appendAutopilotLogEntry } from '../storage/autopilot-log-store.js';
// ---------------------------------------------------------------------------
// Host resolution
// ---------------------------------------------------------------------------
/** Resolve 'auto' host to a concrete HostId. Falls back to 'claude-code'. */
function resolveHost(input) {
    if (input.host !== 'auto') {
        return input.host;
    }
    const detected = detectHost();
    if (detected === 'codex') {
        return 'codex';
    }
    if (detected === 'gemini') {
        return 'gemini';
    }
    // cursor, universal, claude-code → default to claude-code
    return 'claude-code';
}
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
export async function handleCreateRule(input) {
    const { projectPath, name, content, overwriteExisting } = input;
    const host = resolveHost(input);
    // Build a minimal UniversalRule-compatible object for writeRuleForHost
    const rule = {
        id: name,
        name,
        description: '',
        category: 'workflow',
        applicableHosts: [host],
        defaultEnabled: false,
        buildContent: (_h) => content,
    };
    // Compute the expected target path for claude-code (to check overwrite protection)
    let targetPath;
    if (host === 'claude-code') {
        targetPath = join(projectPath, '.claude', 'rules', `${name}.md`);
    }
    else if (host === 'codex') {
        targetPath = join(projectPath, 'AGENTS.md');
    }
    else {
        targetPath = join(projectPath, '.gemini', 'conventions.md');
    }
    // For claude-code, enforce overwrite protection on distinct content
    if (host === 'claude-code') {
        try {
            const existing = await readFile(targetPath, 'utf-8');
            const existingHash = hashContent(existing);
            const newHash = hashContent(content);
            if (existingHash !== newHash && overwriteExisting !== true) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: `Rule already exists at ${targetPath}. Pass overwriteExisting: true to replace.`,
                        },
                    ],
                    isError: true,
                };
            }
        }
        catch {
            // File doesn't exist yet — proceed normally
        }
    }
    let writtenPath;
    try {
        writtenPath = await writeRuleForHost(rule, projectPath, host);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return {
            content: [{ type: 'text', text: `Failed to write rule: ${msg}` }],
            isError: true,
        };
    }
    // Fire-and-forget autopilot log entry
    const projectId = hashProjectPath(projectPath);
    void appendAutopilotLogEntry(projectId, {
        specId: 'create_rule',
        hookName: 'rule_created',
        result: 'pass',
        timestamp: new Date().toISOString(),
        durationMs: 0,
    });
    return {
        content: [
            {
                type: 'text',
                text: `Rule \`${name}\` written to \`${writtenPath}\` (host: ${host}).`,
            },
        ],
        isError: false,
    };
}
//# sourceMappingURL=create-rule.js.map