"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadResolutionCreateConfig = loadResolutionCreateConfig;
exports.draftResolutionIssueFields = draftResolutionIssueFields;
const control_plane_config_1 = require("../config/control-plane-config");
const catalog_1 = require("../i18n/catalog");
const runtime_1 = require("../worker/runtime");
const MAX_RESOLUTION_DRAFT_TITLE_LENGTH = 100;
async function loadResolutionCreateConfig(cwd) {
    try {
        return await (0, control_plane_config_1.loadConfig)(cwd);
    }
    catch (error) {
        if (isEmptyWorkersConfigError(error)) {
            throw new Error((0, catalog_1.translate)(catalog_1.DEFAULT_APP_LOCALE, "issue.command.create.noWorker"));
        }
        throw error;
    }
}
async function draftResolutionIssueFields(input) {
    if ((0, control_plane_config_1.resolveWorkersForPurpose)(input.config, "thinking").length === 0) {
        throw new Error((0, catalog_1.translate)(input.locale, "issue.command.create.noWorker"));
    }
    const workerRuntime = await (0, runtime_1.createConfiguredWorkerRuntime)(input.config, input.homeDirectory === undefined
        ? {}
        : { homeDirectory: input.homeDirectory });
    const draftResult = await workerRuntime.runIssueDraft({
        prompt: buildResolutionIssueDraftPrompt(input),
        outputLanguage: input.config.i18n.defaultLanguage,
        acceptedAt: new Date().toISOString(),
        displayTimeZone: input.config.i18n.displayTimeZone,
        availableIssueTemplates: [],
        workspacePath: input.cwd,
        repositoryRoot: input.cwd,
    });
    if (draftResult.kind === "deferred") {
        throw new Error((0, catalog_1.translate)(input.locale, "issue.command.create.workerDeferred", {
            cooldownUntil: draftResult.cooldownUntil ?? "-",
        }));
    }
    return {
        title: normalizeResolutionTitle({
            title: draftResult.launchResult.draft.title,
            kind: input.kind,
        }),
        capability: normalizeResolutionCapability({
            capability: draftResult.launchResult.draft.body,
            fallback: input.prompt,
        }),
    };
}
function buildResolutionIssueDraftPrompt(input) {
    const issueKind = input.kind === "mcp" ? "MCP-resolution" : "skill-resolution";
    const capabilityKind = input.kind === "mcp"
        ? "missing reusable MCP server/tool capability"
        : "missing reusable skill capability";
    return [
        `Draft a concise ${issueKind} issue title and capability summary from the request below.`,
        `The command will build the final marker, workflow binding, checklist, and metadata. Do not include those details.`,
        `Return a title of at most ${MAX_RESOLUTION_DRAFT_TITLE_LENGTH} characters.`,
        `Return the body as one or two short sentences describing only the ${capabilityKind}. Do not use headings or checklists.`,
        `Target workers: ${formatResolutionDraftTargets(input)}.`,
        "Original request:",
        "```text",
        input.prompt,
        "```",
    ].join("\n");
}
function formatResolutionDraftTargets(input) {
    return input.target === "all"
        ? (0, control_plane_config_1.getConfiguredWorkerProviders)(input.config).join(", ")
        : input.target;
}
function normalizeResolutionTitle(input) {
    const fallback = input.kind === "mcp"
        ? "Resolve MCP server support"
        : "Resolve reusable skill support";
    const normalized = input.title.replace(/\s+/g, " ").trim() || fallback;
    if (normalized.length <= MAX_RESOLUTION_DRAFT_TITLE_LENGTH) {
        return normalized;
    }
    return `${normalized
        .slice(0, MAX_RESOLUTION_DRAFT_TITLE_LENGTH - 3)
        .trimEnd()}...`;
}
function normalizeResolutionCapability(input) {
    return input.capability.trim() || input.fallback.trim();
}
function isEmptyWorkersConfigError(error) {
    const issues = readZodIssues(error);
    return issues.length > 0 && issues.every(isEmptyWorkersConfigIssue);
}
function isEmptyWorkersConfigIssue(issue) {
    const path = issue.path;
    return (Array.isArray(path) &&
        path.length === 2 &&
        path[0] === "workers" &&
        path[1] === "default" &&
        issue.code === "too_small");
}
function readZodIssues(error) {
    if (typeof error !== "object" || error === null || !("issues" in error)) {
        return [];
    }
    const issues = error.issues;
    return Array.isArray(issues) ? issues : [];
}
