"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildWorkerWorkflowTemplateFitReviewContract = buildWorkerWorkflowTemplateFitReviewContract;
exports.validateWorkerWorkflowTemplateFitReviewSemanticRules = validateWorkerWorkflowTemplateFitReviewSemanticRules;
const zod_1 = require("zod");
const structured_contract_support_1 = require("./structured-contract-support");
const types_1 = require("./types");
const validation_issues_1 = require("./validation-issues");
const workerWorkflowTemplateFitReviewSchema = zod_1.z
    .object({
    action: zod_1.z
        .enum([
        types_1.WORKER_WORKFLOW_TEMPLATE_FIT_REVIEW_ACTIONS.useSelected,
        types_1.WORKER_WORKFLOW_TEMPLATE_FIT_REVIEW_ACTIONS.updateSelected,
        types_1.WORKER_WORKFLOW_TEMPLATE_FIT_REVIEW_ACTIONS.createNew,
    ])
        .describe("Fit review action for the selected workflow template."),
    reason: zod_1.z.string().trim().min(1).describe("Concise fit review reason."),
    evidence: zod_1.z
        .array(zod_1.z.string().trim().min(1))
        .min(1)
        .describe("Concrete evidence from the parent request or selected template."),
    recommendedPrompt: zod_1.z
        .string()
        .trim()
        .min(1)
        .nullable()
        .describe("Prompt for the setup issue when action is update_selected or create_new; null for use_selected."),
})
    .strict()
    .describe("Workflow template fit review result.");
function buildWorkerWorkflowTemplateFitReviewContract(input) {
    return (0, structured_contract_support_1.buildWorkerStructuredContract)({
        schema: workerWorkflowTemplateFitReviewSchema,
        example: buildWorkerWorkflowTemplateFitReviewExample(input),
        rules: buildWorkerWorkflowTemplateFitReviewRules(),
    });
}
function validateWorkerWorkflowTemplateFitReviewSemanticRules(review, _input) {
    const issues = [];
    if (review.action ===
        types_1.WORKER_WORKFLOW_TEMPLATE_FIT_REVIEW_ACTIONS.updateSelected ||
        review.action === types_1.WORKER_WORKFLOW_TEMPLATE_FIT_REVIEW_ACTIONS.createNew) {
        if (review.recommendedPrompt === null) {
            (0, validation_issues_1.addWorkerSemanticValidationIssue)(issues, {
                path: ["recommendedPrompt"],
                message: "recommendedPrompt is required when action is update_selected or create_new.",
            });
        }
    }
    else if (review.recommendedPrompt !== null) {
        (0, validation_issues_1.addWorkerSemanticValidationIssue)(issues, {
            path: ["recommendedPrompt"],
            message: "recommendedPrompt must be null when action is use_selected.",
        });
    }
    return issues;
}
function buildWorkerWorkflowTemplateFitReviewExample(input) {
    if (hasSelectedTemplateNarrowingSignal(input)) {
        return {
            action: types_1.WORKER_WORKFLOW_TEMPLATE_FIT_REVIEW_ACTIONS.createNew,
            reason: `${input.selectedTemplate.path} appears to narrow the parent request before planning can begin.`,
            evidence: [
                "The selected template wording limits the workflow scope more than the parent request does.",
            ],
            recommendedPrompt: "Create or update a reusable workflow template that can satisfy the parent request without narrowing the requested outcome.",
        };
    }
    return {
        action: types_1.WORKER_WORKFLOW_TEMPLATE_FIT_REVIEW_ACTIONS.useSelected,
        reason: `${input.selectedTemplate.path} matches the parent request without narrowing the requested outcome.`,
        evidence: [
            "The selected template goal matches the parent request's reusable work type.",
        ],
        recommendedPrompt: null,
    };
}
function hasSelectedTemplateNarrowingSignal(input) {
    const requestText = normalizeFitReviewText(`${input.issue.title}\n${input.issue.body}`);
    const templateText = normalizeFitReviewText(`${input.selectedTemplate.description ?? ""}\n${input.selectedTemplate.body}`);
    return (isBroadOutcomeRequest(requestText) &&
        templateTextContainsNarrowingSignal(templateText));
}
function normalizeFitReviewText(value) {
    return value.toLocaleLowerCase();
}
function isBroadOutcomeRequest(value) {
    return /(?:improve|enhance|revise|review|redesign|readme|user|audience|改善|見直|レビュー|ユーザ|ユーザー)/u.test(value);
}
function templateTextContainsNarrowingSignal(value) {
    return /(?:one small|single .*problem|maintenance-only|review-only|implementation-only|formatting-only|small documentation|minor fix|typo|one .* per run)/u.test(value);
}
function buildWorkerWorkflowTemplateFitReviewRules() {
    return [
        "Return exactly one JSON object in the decision block.",
        "The example is only a schema example; choose the action from the actual parent request and template evidence.",
        "Choose use_selected when the selected template's goal, rules, required process, and success criteria can satisfy the parent request without narrowing or contradicting it.",
        "Choose update_selected when the selected template is the right reusable workflow type but its wording, constraints, selection metadata, or success criteria need a bounded update before the parent issue should run.",
        "Choose create_new when the selected template represents a materially different reusable workflow type, would force the parent request into the wrong scope, or another suitable reusable type is missing.",
        "Treat template Goal, Do, Do Not, Required Process, Handoff, and Success Criteria sections as authoritative fit evidence.",
        "Treat capability availability evidence as authoritative: if the selected template requires unavailable, excluded, or materially overbroad skills/MCP for the parent request, choose update_selected or create_new instead of use_selected.",
        "If template rules such as one-small-change, maintenance-only, review-only, or implementation-only would make the parent request incomplete, do not choose use_selected.",
        "recommendedPrompt must be null for use_selected.",
        "For update_selected or create_new, recommendedPrompt must be a concise workflow authoring prompt based on the parent request and fit evidence.",
    ];
}
