"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveRequiredSkillPreWorkerGate = resolveRequiredSkillPreWorkerGate;
const control_plane_config_1 = require("../../config/control-plane-config");
const runtime_failover_1 = require("../../worker/runtime-failover");
const required_skills_1 = require("../../workflows/required-skills");
const preflight_resolution_marker_1 = require("./preflight-resolution-marker");
const preflight_resolution_plans_1 = require("./preflight-resolution-plans");
const run_state_helpers_1 = require("./run-state-helpers");
async function resolveRequiredSkillPreWorkerGate(input) {
    if ((0, preflight_resolution_marker_1.isPreflightResolutionIssue)(input.issue)) {
        return null;
    }
    if (input.linkedIssue !== undefined &&
        input.linkedIssue !== null &&
        (0, preflight_resolution_marker_1.isPreflightResolutionIssue)(input.linkedIssue)) {
        return null;
    }
    const requiredSkillRefs = (0, run_state_helpers_1.collectWorkflowRequiredSkillIdsForGate)(input.workflow);
    if (requiredSkillRefs.length === 0) {
        return null;
    }
    const report = await (0, required_skills_1.checkRequiredSkillAvailability)({
        repoRoot: input.repoRoot,
        workers: (0, control_plane_config_1.resolveWorkersForPurpose)(input.effectiveConfig, (0, runtime_failover_1.resolveWorkerRuntimePurposeForWorkflowMode)(input.workflow.mode)),
        skillRefs: requiredSkillRefs,
    });
    if (report.ok) {
        return null;
    }
    const locale = input.effectiveConfig.i18n.defaultLanguage;
    const summary = (0, required_skills_1.formatRequiredSkillAvailabilityReport)({ report, locale });
    if (input.effectiveConfig.approvals.requirementsSetup.skills === "confirm") {
        return { kind: "handoff", summary };
    }
    const unresolvedRequiredSkillRefs = report.runnableWorkers.length === 0
        ? report.skillRefs
        : [...new Set(report.missing.map((entry) => entry.skillRef))].sort();
    return {
        kind: "preflight",
        summary,
        resolution: (0, preflight_resolution_plans_1.buildRequiredSkillsPreflightResolution)({
            parentIssue: input.issue,
            workflowTemplateName: input.workflowTemplateName,
            requiredSkillRefs: unresolvedRequiredSkillRefs,
            summary,
            locale,
        }),
    };
}
