"use strict";
/**
 * /goal slash-command handler.
 *
 * Recognises `/goal <intent>` in a chat message, expands the intent via
 * goalExpander, optionally appends the generated tasks to the plan file,
 * and returns a chat-ready response. Kept as a pure-ish module so the
 * chat endpoint can stay thin and so we can unit-test the slash contract
 * without spinning up the whole web stack.
 *
 * Supported forms:
 *   /goal Build a wiki from D:\big.pdf
 *   /goal --dry Research https://acme.example.com
 *   /goal --plan some-plan.md Set up a 9am check-in
 *
 * Dry runs never touch the filesystem — they just return the proposed
 * tasks so the user can review before committing.
 */
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.tryGoalSlashCommand = tryGoalSlashCommand;
const fs = __importStar(require("node:fs/promises"));
const path = __importStar(require("node:path"));
const goalExpander_1 = require("./goalExpander");
const COMMAND_PATTERN = /^\s*\/goal\b\s*(.*)$/s;
function parseGoalArgs(raw) {
    const tokens = raw.split(/\s+/).filter(Boolean);
    let dry = false;
    let planPath = 'IMPLEMENTATION_PLAN.md';
    const rest = [];
    for (let i = 0; i < tokens.length; i++) {
        const t = tokens[i];
        if (t === '--dry' || t === '-n')
            dry = true;
        else if (t === '--plan' || t === '-p')
            planPath = tokens[++i] ?? planPath;
        else
            rest.push(t);
    }
    return { dry, planPath, intent: rest.join(' ').trim() };
}
async function discoverExistingIds(planAbsPath, fsHooks) {
    try {
        await fsHooks.access(planAbsPath);
    }
    catch {
        return [];
    }
    let text;
    try {
        text = await fsHooks.readFile(planAbsPath);
    }
    catch {
        return [];
    }
    const ids = [];
    for (const line of text.split(/\r?\n/)) {
        const m = line.match(/^- \[.\] (\S+)\s+[—-]/);
        if (m)
            ids.push(m[1]);
    }
    return ids;
}
/**
 * Try to handle a chat message as a /goal command. Returns
 * `{ handled: false }` for any message that isn't /goal so callers can
 * fall through to the normal chat path.
 */
async function tryGoalSlashCommand(messageText, options) {
    const match = messageText.match(COMMAND_PATTERN);
    if (!match)
        return { handled: false, response: '', mutated: false, tasks: [] };
    const fsHooks = options.fs ?? {
        readFile: (p) => fs.readFile(p, 'utf-8'),
        appendFile: (p, d) => fs.appendFile(p, d, 'utf-8'),
        writeFile: (p, d) => fs.writeFile(p, d, 'utf-8'),
        access: (p) => fs.access(p),
    };
    const { dry, planPath, intent } = parseGoalArgs(match[1] ?? '');
    if (!intent) {
        return {
            handled: true,
            mutated: false,
            tasks: [],
            response: '**`/goal` — turn a high-level intent into autonomy tasks.**\n\n' +
                'Usage:\n' +
                '```\n' +
                '/goal Build a wiki from D:\\big.pdf\n' +
                '/goal --dry Research https://acme.example.com\n' +
                '/goal --plan some-plan.md Set up a 9am check-in\n' +
                '```\n\n' +
                'Tip: run `--dry` first to preview the tasks before they hit the plan.',
        };
    }
    const planAbsPath = path.resolve(options.projectDir, planPath);
    const existingIds = await discoverExistingIds(planAbsPath, fsHooks);
    const result = (0, goalExpander_1.expandGoal)(intent, { existingIds });
    if (result.tasks.length === 0) {
        return {
            handled: true,
            mutated: false,
            tasks: [],
            response: `_Could not derive any tasks from intent: "${intent}". Try rephrasing with a verb like "build", "research", or "ingest"._`,
        };
    }
    const block = (0, goalExpander_1.renderTasksAsPlanMarkdown)(result.tasks);
    const lines = [];
    lines.push(`**\`/goal\` → detected intent: \`${result.shape}\`**`);
    lines.push('');
    lines.push(`_${result.rationale}_`);
    lines.push('');
    lines.push('```markdown');
    lines.push(block.trimEnd());
    lines.push('```');
    if (dry) {
        lines.push('');
        lines.push(`_Dry run — \`${planPath}\` not modified. Re-run without \`--dry\` to commit._`);
        return { handled: true, mutated: false, tasks: result.tasks, response: lines.join('\n') };
    }
    let exists = true;
    try {
        await fsHooks.access(planAbsPath);
    }
    catch {
        exists = false;
    }
    if (exists) {
        const current = await fsHooks.readFile(planAbsPath);
        const sep = current.endsWith('\n') ? '' : '\n';
        await fsHooks.appendFile(planAbsPath, sep + block);
    }
    else {
        await fsHooks.writeFile(planAbsPath, '# Implementation Plan\n\n' + block);
    }
    lines.push('');
    lines.push(`✅ Appended **${result.tasks.length}** task(s) to \`${planPath}\`. Start the autonomy loop to begin work.`);
    return { handled: true, mutated: true, tasks: result.tasks, response: lines.join('\n') };
}
//# sourceMappingURL=goalSlashCommand.js.map