import { buildActionDecisionMatrix, buildBreakingChangePatterns, buildTestAssessmentGuidelines, buildAddRecommendationGuidelines, buildDriftOutputChecklist, buildUpdateExecutionRules, } from "./driftAnalysisSections.js";
import { isTestbotEnabled } from "../../utils/featureFlags.js";
import { readDiffFile } from "../../utils/utils.js";
export function buildDriftAnalysisPrompt(params) {
    const { existingTests, scannedEndpoints, repositoryPath, stateFile, routerMountContext, candidateRouteFiles, diffFilePath } = params;
    // Read raw diff once — used for both the inline summary block and the per-line file reference.
    const rawDiff = readDiffFile(diffFilePath);
    let newEndpointCount = 0;
    let diffSection = "";
    if (rawDiff) {
        const lines = rawDiff.split("\n");
        const newEndpointMatch = rawDiff.match(/\*\*New Endpoints\*\*\s+\((\d+)\)/);
        if (newEndpointMatch)
            newEndpointCount = parseInt(newEndpointMatch[1], 10);
        diffSection = `## Branch Diff
\`\`\`
${lines.slice(0, 200).join("\n")}
\`\`\`
`;
    }
    const testListSection = existingTests.length > 0
        ? `## Existing Test Files (${existingTests.length})
${existingTests.map((t) => `- ${t.testFile} (${t.testType})`).join("\n")}
`
        : `## Existing Test Files
No existing Skyramp tests found in repository.
`;
    const scannedSection = scannedEndpoints.length > 0
        ? `## Scanned Endpoints (${scannedEndpoints.length})
Note: paths below come from static analysis and may be incomplete for nested resources or unsupported frameworks. Use the Routing entry-point files section below to verify and reconstruct full paths.
${scannedEndpoints.map((ep) => {
            let methods;
            if (Array.isArray(ep.methods)) {
                methods = ep.methods.map((m) => (typeof m === "string" ? m : m.method)).join("|");
            }
            else {
                methods = ep.method;
            }
            return `- ${methods} ${ep.path}`;
        }).join("\n")}
`
        : "";
    const mountSection = routerMountContext?.length
        ? `## Routing entry-point files
Read these to trace the full router/module hierarchy when verifying endpoint paths:
${routerMountContext.map(f => `- \`${f}\``).join("\n")}
`
        : "";
    const hasJavaFiles = candidateRouteFiles?.some(f => /\.(java|kt)$/.test(f)) ?? false;
    const candidateFilesSection = candidateRouteFiles && candidateRouteFiles.length > 0
        ? `## Route Files (read these to find endpoints from any framework)
${candidateRouteFiles.map(f => `- ${f}`).join("\n")}
${hasJavaFiles ? "Note — Java Spring: full URL = class-level `@RequestMapping` prefix + method-level path. If the prefix is a constant reference (e.g. `@RequestMapping(Url.PAGE_URL)`), find the constant — same file, inner class, or a separate `Url.java` — and resolve it (including `+` concatenation)." : ""}
`
        : "";
    const diffFileSection = diffFilePath
        ? `## Raw Diff File
Read \`${diffFilePath}\` to get the full line-by-line diff. Use it to detect:
- Additive response fields: lines starting with \`+\` inside a view/serializer/controller (e.g. \`+ "newField":\`, \`+ newField =\`)
- Renamed routes: \`-  @app.route("/old")\` / \`+  @app.route("/new")\` or similar framework patterns
- Status code changes: \`- return 200\` / \`+ return 201\`, \`- res.status(200)\` / \`+ res.status(204)\`
- Auth additions/removals: \`+ @require_auth\`, \`- @login_required\`, middleware changes
Read the file once and cache its contents — it is the primary source for per-line breaking-change detection. Use it as evidence for Checks A–D below.
`
        : "";
    // In inline mode (testbot), skip the context header — existing tests and diff
    // are provided by skyramp_analyze_changes at runtime, not at prompt-build time.
    const contextSection = isTestbotEnabled()
        ? ""
        : `# Test Health Analysis

**Repository**: \`${repositoryPath}\`
**Existing tests**: ${existingTests.length}
**New endpoints in diff**: ${newEndpointCount}

${diffSection}
${diffFileSection}
${testListSection}
${scannedSection}
${mountSection}
${candidateFilesSection}`;
    if (isTestbotEnabled()) {
        // Testbot inline mode: all maintenance logic lives here so the testbot
        // prompt only orchestrates steps without duplicating rules.
        // No persona statement here — the outer testbot prompt already establishes
        // the agent's context; a nested identity statement causes role confusion.
        return `<drift_analysis_rules>
${buildActionDecisionMatrix()}
${buildUpdateExecutionRules()}
${buildDriftOutputChecklist(existingTests.length, newEndpointCount, isTestbotEnabled())}
</drift_analysis_rules>`;
    }
    return `You are acting as a Skyramp Integration Architect. Your responsibility is to assess each existing test against the branch diff and determine the correct maintenance action.

${contextSection}
${buildActionDecisionMatrix()}
${buildBreakingChangePatterns()}
${buildTestAssessmentGuidelines()}
${buildUpdateExecutionRules()}
${buildAddRecommendationGuidelines()}
${buildDriftOutputChecklist(existingTests.length, newEndpointCount, isTestbotEnabled(), stateFile)}`;
}
