import { z } from "zod";
import { StructuredAgentFallbackError, StructuredAgentResponseError, generateStructuredAgentResponseWithFallback, } from "./agent/agent-response-loop.js";
import { resolveStructuredGenerationProviders, } from "./agent/structured-generation-providers.js";
import { buildAgentBranchNameSeed } from "./agent/prompt-attachments.js";
import { buildMetadataPrompt } from "../utils/build-metadata-prompt.js";
const BranchNameSchema = z.object({
    branch: z.string().min(1).max(100),
});
async function buildPrompt(seed, options) {
    return buildMetadataPrompt({
        cwd: options.cwd,
        workspaceGitService: options.workspaceGitService,
        configKey: "branchName",
        before: [
            "Generate a git branch name for a coding agent based on the user prompt and attachments.",
            "Branch: concise lowercase slug using letters, numbers, hyphens, and slashes only.",
            "No spaces, no uppercase, no leading or trailing hyphen, no consecutive hyphens.",
        ].join("\n"),
        after: "Return JSON only with a single field 'branch'.",
        trailing: `User context:\n${seed}`,
    });
}
export async function generateBranchNameFromFirstAgentContext(options) {
    const seed = buildAgentBranchNameSeed(options.firstAgentContext);
    if (!seed) {
        return null;
    }
    const generator = options.deps?.generateStructuredAgentResponseWithFallback ??
        generateStructuredAgentResponseWithFallback;
    try {
        const providers = options.providerSnapshotManager
            ? await resolveStructuredGenerationProviders({
                cwd: options.cwd,
                providerSnapshotManager: options.providerSnapshotManager,
                daemonConfig: options.daemonConfig,
                currentSelection: options.currentSelection,
            })
            : [];
        const result = await generator({
            manager: options.agentManager,
            cwd: options.cwd,
            prompt: await buildPrompt(seed, {
                cwd: options.cwd,
                workspaceGitService: options.workspaceGitService,
            }),
            schema: BranchNameSchema,
            schemaName: "BranchName",
            maxRetries: 2,
            providers,
            persistSession: false,
            logger: options.logger,
            agentConfigOverrides: {
                title: "Branch name generator",
                internal: true,
            },
        });
        return result.branch.trim() || null;
    }
    catch (error) {
        const attempts = error instanceof StructuredAgentFallbackError ? error.attempts : undefined;
        options.logger.error({ err: error, attempts }, error instanceof StructuredAgentResponseError || error instanceof StructuredAgentFallbackError
            ? "Structured branch name generation failed"
            : "Branch name generation failed");
        return null;
    }
}
//# sourceMappingURL=worktree-branch-name-generator.js.map