"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderRepairSectionLines = renderRepairSectionLines;
exports.renderIssueDraftRepairSectionLines = renderIssueDraftRepairSectionLines;
exports.renderEventHookDraftRepairSectionLines = renderEventHookDraftRepairSectionLines;
exports.renderTemplateDraftRepairSectionLines = renderTemplateDraftRepairSectionLines;
exports.renderTemplateUpdateRepairSectionLines = renderTemplateUpdateRepairSectionLines;
exports.renderAiWorkflowOptionAutofillRepairSectionLines = renderAiWorkflowOptionAutofillRepairSectionLines;
exports.renderFollowupProposalReviewRepairSectionLines = renderFollowupProposalReviewRepairSectionLines;
exports.renderWorkflowTemplateFitReviewRepairSectionLines = renderWorkflowTemplateFitReviewRepairSectionLines;
exports.renderWorkflowPlanReviewRepairSectionLines = renderWorkflowPlanReviewRepairSectionLines;
exports.renderPullRequestReviewNecessityRepairSectionLines = renderPullRequestReviewNecessityRepairSectionLines;
const decision_contract_rules_1 = require("./decision-contract-rules");
const prompt_text_1 = require("./prompt-text");
const structured_contract_support_1 = require("./structured-contract-support");
const structured_draft_metadata_1 = require("./structured-draft-metadata");
const workflow_planning_fields_1 = require("./workflow-planning-fields");
function renderRepairSectionLines(repairContext, contract) {
    if (!repairContext) {
        return [];
    }
    const relevantRepairGuidance = renderRelevantRepairGuidance(repairContext, contract);
    return [
        "- This is a repair-only retry.",
        "- Do not inspect files, run commands, delegate subagents, or change response intent, step order, or semantics.",
        repairContext.kind === "semantic_invalid"
            ? "- Preserve the intent of the previous response and make only the minimum contract fix needed to satisfy the validation issues."
            : "- Preserve the intent of the previous response and make only the minimum schema fix.",
        "- For schema errors, remove fields not allowed in this mode; for too_big errors, split offending strings into shorter sibling items, target <=240 characters each.",
        "- Return only corrected decision JSON that matches the contract.",
        "- Previous validation issues:",
        ...renderValidationIssues(repairContext.issues),
        ...relevantRepairGuidance,
        `- ${prompt_text_1.PROMPT_TEXT.fieldPreviousDecisionBlock}:`,
        ...repairContext.previousDecisionBlock
            .split("\n")
            .map((line) => `  ${line}`),
    ];
}
function renderIssueDraftRepairSectionLines(repairContext) {
    return renderStructuredDraftRepairSectionLines(repairContext, structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.issueDraft);
}
function renderEventHookDraftRepairSectionLines(repairContext) {
    return renderStructuredDraftRepairSectionLines(repairContext, structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.eventHookDraft);
}
function renderTemplateDraftRepairSectionLines(repairContext) {
    return renderStructuredDraftRepairSectionLines(repairContext, structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.templateDraft);
}
function renderTemplateUpdateRepairSectionLines(repairContext) {
    return renderStructuredDraftRepairSectionLines(repairContext, structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.templateUpdate);
}
function renderAiWorkflowOptionAutofillRepairSectionLines(repairContext) {
    return renderStructuredDraftRepairSectionLines(repairContext, structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.aiWorkflowOptionAutofill);
}
function renderFollowupProposalReviewRepairSectionLines(repairContext) {
    return renderStructuredDraftRepairSectionLines(repairContext, structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.followupProposalReview);
}
function renderWorkflowTemplateFitReviewRepairSectionLines(repairContext) {
    return renderStructuredDraftRepairSectionLines(repairContext, structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.workflowTemplateFitReview);
}
function renderWorkflowPlanReviewRepairSectionLines(repairContext) {
    return renderStructuredDraftRepairSectionLines(repairContext, structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.workflowPlanReview);
}
function renderPullRequestReviewNecessityRepairSectionLines(repairContext) {
    return renderStructuredDraftRepairSectionLines(repairContext, structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.pullRequestReviewNecessity);
}
function renderStructuredDraftRepairSectionLines(repairContext, metadata) {
    return [
        "- This is a repair-only retry.",
        "- Do not inspect files, run commands, delegate subagents, or change intent.",
        repairContext.kind === "semantic_invalid"
            ? "- Preserve the previous response intent and make only the minimum semantic fix."
            : repairContext.kind === "missing"
                ? metadata.repairPrompt.missingLine
                : "- Preserve the previous response intent and make only the minimum schema fix.",
        metadata.repairPrompt.returnOnlyLine,
        "- Previous validation issues:",
        ...renderValidationIssues(repairContext.issues),
        `- ${prompt_text_1.PROMPT_TEXT.fieldPreviousDecisionBlock}:`,
        ...repairContext.previousDecisionBlock
            .split("\n")
            .map((line) => `  ${line}`),
    ];
}
function renderValidationIssues(validationIssues) {
    if (validationIssues.length === 0) {
        return [`  ${prompt_text_1.PROMPT_TEXT.none}`];
    }
    return validationIssues.map((issue) => {
        const path = issue.path.length > 0 ? issue.path.join(".") : "(root)";
        return `  - ${path}: ${issue.code}: ${issue.message}`;
    });
}
function renderRelevantRepairGuidance(repairContext, contract) {
    const previousDecision = parsePreviousDecisionBlock(repairContext.previousDecisionBlock);
    const schemaLines = renderRelevantSchemaLines(repairContext, contract, previousDecision);
    const ruleLines = renderRelevantRuleLines(repairContext, contract.rules, previousDecision);
    if (schemaLines.length === 0 && ruleLines.length === 0) {
        return [];
    }
    return [
        `- ${prompt_text_1.PROMPT_TEXT.fieldRelevantSchemaExcerpts}:`,
        ...(schemaLines.length > 0 ? schemaLines : [`  ${prompt_text_1.PROMPT_TEXT.none}`]),
        ...(ruleLines.length > 0
            ? [`- ${prompt_text_1.PROMPT_TEXT.fieldRelevantRules}:`, ...ruleLines]
            : []),
    ];
}
function renderRelevantSchemaLines(repairContext, contract, previousDecision) {
    const schemaTargets = collectRelevantSchemaTargets(repairContext.issues, previousDecision);
    return schemaTargets.flatMap((target) => {
        switch (target) {
            case "decision":
                return renderSchemaBlock(prompt_text_1.PROMPT_TEXT.fieldDecisionSchema, contract.promptSchema);
            case "task":
                return renderSchemaBlock(prompt_text_1.PROMPT_TEXT.fieldTaskStepSchema, contract.stepPromptSchemas.task);
            case "workflow_ref":
                return renderSchemaBlock(prompt_text_1.PROMPT_TEXT.fieldWorkflowRefStepSchema, contract.stepPromptSchemas.workflowRef);
            case "child_issue":
                return renderSchemaBlock(prompt_text_1.PROMPT_TEXT.fieldChildIssueStepSchema, contract.stepPromptSchemas.childIssue);
            default:
                return [];
        }
    });
}
function renderRelevantRuleLines(repairContext, contractRules, previousDecision) {
    const rules = collectRelevantRuleTexts(repairContext.issues, previousDecision, contractRules);
    return rules.map((rule) => `  - ${rule}`);
}
function renderSchemaBlock(label, schema) {
    return [
        `  - ${label}:`,
        ...(0, structured_contract_support_1.renderWorkerPromptJsonSchemaForDisplay)(schema)
            .split("\n")
            .map((line) => `    ${line}`),
    ];
}
function collectRelevantSchemaTargets(issues, previousDecision) {
    const targets = new Set();
    for (const issue of issues) {
        if (issue.path[0] === "plan" &&
            issue.path[1] === "steps" &&
            typeof issue.path[2] === "number") {
            const stepKind = resolvePreviousStepKind(previousDecision, issue.path[2]);
            if (stepKind === "task" ||
                stepKind === "workflow_ref" ||
                stepKind === "child_issue") {
                targets.add(stepKind);
            }
            else {
                targets.add("decision");
            }
            continue;
        }
        targets.add("decision");
    }
    if (targets.size === 0 && issues.length > 0) {
        targets.add("decision");
    }
    return [...targets];
}
function collectRelevantRuleTexts(issues, previousDecision, contractRules) {
    const rules = new Set();
    for (const issue of issues) {
        if (issue.path[0] === "issueTitle" || issue.path[0] === "contract") {
            maybeAddRule(rules, contractRules, workflow_planning_fields_1.WORKFLOW_PLANNING_REQUIRED_PROCEED_RULE);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.issueTitle);
            continue;
        }
        if (issue.path[0] === "plan" || issue.path[0] === "planPatch") {
            maybeAddRule(rules, contractRules, issue.path[0] === "planPatch"
                ? workflow_planning_fields_1.WORKFLOW_REPLANNING_REQUIRED_PROCEED_RULE
                : workflow_planning_fields_1.WORKFLOW_PLANNING_REQUIRED_PROCEED_RULE);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.topLevelFields);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.noAdministrativeSteps);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.persistedArtifactSources);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.persistedArtifactExclusions);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.followupSeed);
        }
        if (issue.path[0] === "executionGuidance") {
            maybeAddRule(rules, contractRules, workflow_planning_fields_1.WORKFLOW_PLANNING_REQUIRED_PROCEED_RULE);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.persistedArtifactSources);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.persistedArtifactExclusions);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.executionGuidance);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.executionGuidanceContent);
            continue;
        }
        if (issue.path[0] === "predictedTouchedPaths") {
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.predictedTouchedPaths);
            maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.predictedTouchedPathsFinal);
            continue;
        }
        if (issue.path[0] === "plan" &&
            issue.path[1] === "steps" &&
            typeof issue.path[2] === "number") {
            maybeAddRule(rules, contractRules, "Each plan step must set kind explicitly to task, workflow_ref, or child_issue.");
            const stepKind = resolvePreviousStepKind(previousDecision, issue.path[2]);
            if (stepKind === "task") {
                maybeAddRule(rules, contractRules, "Task steps must omit targetTemplateName, callSiteId, sourceTemplateName, sourceTemplateDigest, and expansionGroupId.");
                continue;
            }
            if (stepKind === "child_issue") {
                maybeAddRule(rules, contractRules, decision_contract_rules_1.WORKFLOW_PLAN_RULES.childIssueDelegation);
                continue;
            }
            if (stepKind !== "workflow_ref") {
                continue;
            }
            maybeAddRule(rules, contractRules, "Each workflow_ref step must include a human-facing title plus non-empty targetTemplateName, callSiteId, sourceTemplateName, sourceTemplateDigest, and expansionGroupId.");
            maybeAddRule(rules, contractRules, "When direct child workflow call sites are listed, emit exactly one workflow_ref step for each listed call site and preserve their order.");
        }
    }
    return [...rules];
}
function maybeAddRule(output, contractRules, expectedRule) {
    const matchedRule = contractRules.find((rule) => rule === expectedRule);
    if (matchedRule) {
        output.add(matchedRule);
    }
}
function parsePreviousDecisionBlock(previousDecisionBlock) {
    try {
        return JSON.parse(previousDecisionBlock);
    }
    catch {
        return null;
    }
}
function resolvePreviousStepKind(previousDecision, stepIndex) {
    if (!previousDecision || typeof previousDecision !== "object") {
        return null;
    }
    const plan = previousDecision.plan;
    if (!plan || typeof plan !== "object") {
        return null;
    }
    const steps = plan.steps;
    if (!Array.isArray(steps)) {
        return null;
    }
    const step = steps[stepIndex];
    if (!step || typeof step !== "object") {
        return null;
    }
    const kind = step.kind;
    return kind === "task" || kind === "workflow_ref" || kind === "child_issue"
        ? kind
        : null;
}
