import fs from "node:fs/promises";
import { DEFAULT_SYSTEM_PROMPT } from "./config.js";
import { createFileSections, readFiles } from "./files.js";
import { formatFileSections } from "./markdown.js";
import { createFsAdapter } from "./fsAdapter.js";
export function buildPrompt(basePrompt, files, cwd = process.cwd()) {
    if (!files.length) {
        return basePrompt;
    }
    const sections = createFileSections(files, cwd);
    const sectionText = formatFileSections(sections, { includeFileIndex: true });
    return `${basePrompt.trim()}\n\n${sectionText}`;
}
export function buildRequestBody({ modelConfig, reasoningEffort, reasoningMode, systemPrompt, userPrompt, searchEnabled, maxOutputTokens, background, storeResponse, previousResponseId, }) {
    const searchToolType = modelConfig.searchToolType ?? "web_search_preview";
    const reasoning = modelConfig.reasoning || reasoningEffort || reasoningMode
        ? {
            ...(modelConfig.reasoning ?? {}),
            ...(reasoningEffort ? { effort: reasoningEffort } : {}),
            ...(reasoningMode ? { mode: reasoningMode } : {}),
        }
        : undefined;
    return {
        model: modelConfig.apiModel ?? modelConfig.model,
        previous_response_id: previousResponseId ? previousResponseId : undefined,
        instructions: systemPrompt,
        input: [
            {
                role: "user",
                content: [
                    {
                        type: "input_text",
                        text: userPrompt,
                    },
                ],
            },
        ],
        tools: searchEnabled ? [{ type: searchToolType }] : undefined,
        reasoning,
        max_output_tokens: maxOutputTokens,
        background: background ? true : undefined,
        store: storeResponse ? true : undefined,
    };
}
export async function renderPromptMarkdown(options, deps = {}) {
    const cwd = deps.cwd ?? process.cwd();
    const fsModule = deps.fs ?? createFsAdapter(fs);
    const files = await readFiles(options.file ?? [], {
        cwd,
        fsModule,
        maxFileSizeBytes: options.maxFileSizeBytes,
    });
    const sections = createFileSections(files, cwd);
    const systemPrompt = options.system?.trim() || DEFAULT_SYSTEM_PROMPT;
    const userPrompt = (options.prompt ?? "").trim();
    const lines = ["[SYSTEM]", systemPrompt, ""];
    lines.push("[USER]", userPrompt, "");
    lines.push(formatFileSections(sections));
    return lines
        .join("\n")
        .replace(/\n{3,}/g, "\n\n")
        .trimEnd();
}
