import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { configDir } from '../config.js';
const INSTRUCTION_FILES = ['CHEAPCODE.md', 'AGENTS.md', 'CLAUDE.md'];
const MAX_FILE_CHARS = 20_000;
function firstInstructionFile(dir) {
    for (const name of INSTRUCTION_FILES) {
        const file = path.join(dir, name);
        try {
            if (fs.existsSync(file)) {
                return { name, text: fs.readFileSync(file, 'utf8').slice(0, MAX_FILE_CHARS) };
            }
        }
        catch {
            /* unreadable; try next */
        }
    }
    return null;
}
function gitRoot(cwd) {
    try {
        return execFileSync('git', ['rev-parse', '--show-toplevel'], {
            cwd,
            encoding: 'utf8',
            timeout: 3000,
            stdio: ['ignore', 'pipe', 'pipe'],
        }).trim();
    }
    catch {
        return null;
    }
}
/**
 * Layered instructions, most general first:
 * 1. Global: ~/.config/cheapcode/CHEAPCODE.md (user's personal rules, all projects)
 * 2. Repo root: first of CHEAPCODE.md / AGENTS.md / CLAUDE.md
 * 3. cwd (when different from repo root): same lookup
 */
export function gatherInstructions(cwd) {
    const sections = [];
    const globalFile = path.join(configDir(), 'CHEAPCODE.md');
    try {
        if (fs.existsSync(globalFile)) {
            sections.push(`## Global instructions (from ~/.config/cheapcode/CHEAPCODE.md)\n\n${fs
                .readFileSync(globalFile, 'utf8')
                .slice(0, MAX_FILE_CHARS)}`);
        }
    }
    catch {
        /* skip */
    }
    const root = gitRoot(cwd);
    if (root && root !== cwd) {
        const rootFile = firstInstructionFile(root);
        if (rootFile) {
            sections.push(`## Project instructions (from ${path.join(root, rootFile.name)})\n\n${rootFile.text}`);
        }
    }
    const cwdFile = firstInstructionFile(cwd);
    if (cwdFile) {
        sections.push(`## Project instructions (from ${cwdFile.name})\n\n${cwdFile.text}`);
    }
    return sections;
}
