import "@poe-code/agent-spawn/register-factories";
import { runAutonomousAgent } from "./agent-runner.js";
import { resolveRoleCwd } from "./resolve-cwd.js";
import { buildInspectorSystemPrompt, prependSystemPrompt } from "./system-prompt.js";
import { resolveTemplate } from "./templates.js";
export async function runInspector(name, config, doc, context, options) {
    const userPrompt = options.promptOverride ??
        resolveTemplate(config.prompt, buildTemplateContext(doc, context));
    const systemPrompt = buildInspectorSystemPrompt({
        inspectorName: name,
        ...(context.builder
            ? {
                builder: {
                    summary: context.builder.summary,
                    ...(context.builder.log_path ? { log_path: context.builder.log_path } : {})
                }
            }
            : {})
    });
    const prompt = prependSystemPrompt(systemPrompt, userPrompt);
    const output = await runAutonomousAgent({
        agent: config.agent,
        mode: config.mode,
        prompt,
        cwd: resolveRoleCwd(config, doc.filePath, options.defaultCwd),
        mcpServers: buildMcpServers(doc, config),
        ...(options.logPath ? { logPath: options.logPath } : {}),
        ...(options.signal ? { signal: options.signal } : {})
    });
    const logPath = extractLogPath(output);
    return {
        name,
        summary: extractSummary(output),
        ...(logPath ? { log_path: logPath } : {})
    };
}
function buildMcpServers(doc, config) {
    const merged = Object.assign(Object.create(null), doc.frontmatter.mcp, config.mcp);
    if (Object.keys(merged).length === 0) {
        return undefined;
    }
    const servers = Object.create(null);
    for (const [name, mcpConfig] of Object.entries(merged)) {
        servers[name] = {
            command: mcpConfig.command,
            ...(mcpConfig.args ? { args: [...mcpConfig.args] } : {}),
            ...(mcpConfig.timeout !== undefined ? { timeout: mcpConfig.timeout } : {})
        };
    }
    return servers;
}
export async function runAllInspectors(doc, context, options) {
    const inspectors = doc.frontmatter.inspectors;
    if (inspectors === undefined) {
        return [];
    }
    const inspectorSummaries = { ...(context.inspectors ?? {}) };
    const results = [];
    for (const [name, config] of Object.entries(inspectors)) {
        const result = await runInspector(name, config, doc, {
            ...context,
            inspectors: inspectorSummaries
        }, options);
        results.push(result);
        inspectorSummaries[name] = result.summary;
    }
    return results;
}
function buildTemplateContext(doc, context) {
    return {
        ...context,
        plan: {
            ...(context.plan ?? { path: doc.filePath }),
            path: doc.filePath
        }
    };
}
function extractLogPath(result) {
    if (typeof result === "string")
        return undefined;
    return typeof result.logFile === "string" ? result.logFile : undefined;
}
function extractSummary(result) {
    if (typeof result === "string") {
        return result;
    }
    return (readString(result.summary) ??
        readString(result.output) ??
        readString(result.stdout) ??
        readString(result.text) ??
        "");
}
function readString(value) {
    return typeof value === "string" ? value : undefined;
}
