import { z } from "zod";
import { StructuredAgentFallbackError, StructuredAgentResponseError, generateStructuredAgentResponseWithFallback, } from "./agent-response-loop.js";
import { resolveStructuredGenerationProviders, } from "./structured-generation-providers.js";
import { MAX_AUTO_AGENT_TITLE_CHARS } from "@kong-link/protocol/agent-title-limits";
import { buildMetadataPrompt } from "../../utils/build-metadata-prompt.js";
function hasExplicitTitle(title) {
    return Boolean(title && title.trim().length > 0);
}
function normalizeAutoTitle(title) {
    const normalized = title.trim();
    if (!normalized) {
        return null;
    }
    return normalized.slice(0, MAX_AUTO_AGENT_TITLE_CHARS).trim() || null;
}
export async function determineAgentMetadataNeeds(options) {
    const prompt = options.initialPrompt?.trim();
    if (!prompt) {
        return { prompt: null, needsTitle: false };
    }
    const needsTitle = !hasExplicitTitle(options.explicitTitle);
    return {
        prompt,
        needsTitle,
    };
}
function buildMetadataSchema(needs) {
    if (!needs.needsTitle) {
        return null;
    }
    const shape = {};
    if (needs.needsTitle) {
        shape.title = z.string().min(1).max(MAX_AUTO_AGENT_TITLE_CHARS);
    }
    return z.object(shape);
}
async function buildPrompt(needs, options) {
    const beforeLines = ["Generate metadata for a coding agent based on the user prompt."];
    if (needs.needsTitle) {
        beforeLines.push(`Title: short descriptive label (<= ${MAX_AUTO_AGENT_TITLE_CHARS} chars).`);
    }
    return buildMetadataPrompt({
        cwd: options.cwd,
        workspaceGitService: options.workspaceGitService,
        configKey: "agentTitle",
        before: beforeLines.join("\n"),
        after: "Return JSON only with a single field 'title'.",
        trailing: `User prompt:\n${needs.prompt ?? ""}`,
    });
}
export async function generateAndApplyAgentMetadata(options) {
    const needs = await determineAgentMetadataNeeds(options);
    if (!needs.prompt) {
        return;
    }
    const schema = buildMetadataSchema(needs);
    if (!schema) {
        return;
    }
    const generator = options.deps?.generateStructuredAgentResponseWithFallback ??
        generateStructuredAgentResponseWithFallback;
    let result;
    try {
        const providers = options.providerSnapshotManager
            ? await resolveStructuredGenerationProviders({
                cwd: options.cwd,
                providerSnapshotManager: options.providerSnapshotManager,
                daemonConfig: options.daemonConfig,
                currentSelection: options.currentSelection,
            })
            : [];
        result = await generator({
            manager: options.agentManager,
            cwd: options.cwd,
            prompt: await buildPrompt(needs, {
                cwd: options.cwd,
                workspaceGitService: options.workspaceGitService,
            }),
            schema,
            schemaName: "AgentMetadata",
            maxRetries: 2,
            providers,
            persistSession: false,
            logger: options.logger,
            agentConfigOverrides: {
                title: "Agent metadata generator",
                internal: true,
            },
        });
    }
    catch (error) {
        const attempts = error instanceof StructuredAgentFallbackError ? error.attempts : undefined;
        options.logger.error({ err: error, agentId: options.agentId, attempts }, error instanceof StructuredAgentResponseError || error instanceof StructuredAgentFallbackError
            ? "Structured metadata generation failed"
            : "Agent metadata generation failed");
        return;
    }
    if (needs.needsTitle && typeof result.title === "string") {
        const normalizedTitle = normalizeAutoTitle(result.title);
        if (normalizedTitle) {
            await options.agentManager.setGeneratedTitle(options.agentId, normalizedTitle);
        }
    }
}
export function scheduleAgentMetadataGeneration(options) {
    queueMicrotask(() => {
        void generateAndApplyAgentMetadata(options).catch((error) => {
            options.logger.error({ err: error, agentId: options.agentId }, "Agent metadata generation crashed");
        });
    });
}
//# sourceMappingURL=agent-metadata-generator.js.map