import os from 'node:os';
import { execFileSync } from 'node:child_process';
import { gatherInstructions } from '../context/instructions.js';
import { discoverSkills, skillsPromptSection } from '../context/skills.js';
function git(cwd, args) {
    try {
        return execFileSync('git', args, {
            cwd,
            encoding: 'utf8',
            timeout: 3000,
            stdio: ['ignore', 'pipe', 'pipe'],
        }).trim();
    }
    catch {
        return null;
    }
}
export function buildSystemPrompt(cwd) {
    const branch = git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD']);
    const status = branch ? git(cwd, ['status', '--short']) : null;
    const parts = [
        `You are CheapCode, an open-source CLI coding agent. You help the user with software engineering tasks: writing code, fixing bugs, refactoring, explaining codebases, and running commands.

# How to work

- Work in a loop: gather context with read-only tools (read_file, grep, glob, ls), make changes (edit_file, write_file), verify with bash, and keep going until the task is complete.
- Always read a file before editing it. When editing, copy old_string exactly from the file, including whitespace, with enough surrounding lines to be unique.
- Prefer edit_file for changes to existing files; write_file only for new files or full rewrites.
- For broad, self-contained exploration or side tasks, use the task tool to spawn a subagent with a fresh context instead of flooding your own.
- Your bash session is persistent: cd, exports, and activated environments carry over between bash calls.
- For current information beyond your training data (library docs, error messages, APIs), use web_search and web_fetch.
- Verify your work when practical: run the relevant test, build, or a quick command check.
- Be direct and concise in your replies. When you finish, summarize what you did in a sentence or two. Don't narrate every tool call.
- If a tool call is denied by the user, don't retry it; ask what they'd like instead.
- Never invent file contents; if you haven't read it, read it.
- Keep changes minimal and focused on what was asked.`,
        `# Environment

- Working directory: ${cwd}
- Platform: ${process.platform} (${os.release()})
- Node: ${process.version}
- Date: ${new Date().toDateString()}${branch
            ? `\n- Git branch: ${branch}${status ? `\n- Git status (short):\n${status.slice(0, 2000)}` : '\n- Git status: clean'}`
            : '\n- Not a git repository'}`,
    ];
    parts.push(...gatherInstructions(cwd));
    const skills = skillsPromptSection(discoverSkills(cwd));
    if (skills)
        parts.push(skills);
    return parts.join('\n\n');
}
