import {
  sanitizePath
} from "./chunk-W6Y7ZW3Y.js";
import {
  init_dist,
  paginate
} from "./chunk-77EZGPSR.js";

// src/mcp/tools/review-pipeline.ts
init_dist();

// src/mcp/utils/severity.ts
var SEVERITY_ORDER = {
  error: 0,
  critical: 0,
  warning: 1,
  important: 1,
  info: 2,
  suggestion: 2
};
function sortFindingsBySeverity(findings) {
  return [...findings].sort((a, b) => {
    const aObj = a;
    const bObj = b;
    const aSev = SEVERITY_ORDER[typeof aObj.severity === "string" ? aObj.severity : ""] ?? 99;
    const bSev = SEVERITY_ORDER[typeof bObj.severity === "string" ? bObj.severity : ""] ?? 99;
    return aSev - bSev;
  });
}

// src/mcp/tools/review-pipeline.ts
var runCodeReviewDefinition = {
  name: "run_code_review",
  description: "Run the unified 7-phase code review pipeline: gate, mechanical checks, context scoping, parallel agents, validation, deduplication, and output.",
  inputSchema: {
    type: "object",
    properties: {
      path: { type: "string", description: "Path to project root" },
      diff: { type: "string", description: "Git diff string to review" },
      commitMessage: {
        type: "string",
        description: "Most recent commit message (for change-type detection)"
      },
      comment: {
        type: "boolean",
        description: "Post inline comments to GitHub PR (requires prNumber and repo)"
      },
      ci: {
        type: "boolean",
        description: "Enable eligibility gate and non-interactive output"
      },
      deep: {
        type: "boolean",
        description: "Add threat modeling pass to security agent"
      },
      noMechanical: {
        type: "boolean",
        description: "Skip mechanical checks (useful if already run)"
      },
      prNumber: {
        type: "number",
        description: "PR number (required for --comment and CI gate)"
      },
      repo: {
        type: "string",
        description: "Repository in owner/repo format (required for --comment)"
      },
      offset: {
        type: "number",
        description: "Number of findings to skip (pagination). Default: 0. Findings are sorted by severity desc (critical > important > suggestion)."
      },
      limit: {
        type: "number",
        description: "Max findings to return (pagination). Default: 20."
      }
    },
    required: ["path", "diff"]
  }
};
async function handleRunCodeReview(input) {
  try {
    const { parseDiff, runReviewPipeline } = await import("./dist-TG63OKA5.js");
    const parseResult = parseDiff(input.diff);
    if (!parseResult.ok) {
      return {
        content: [
          {
            type: "text",
            text: `Error parsing diff: ${parseResult.error.message}`
          }
        ],
        isError: true
      };
    }
    const codeChanges = parseResult.value;
    const projectRoot = sanitizePath(input.path);
    const diffInfo = {
      changedFiles: codeChanges.files.map((f) => f.path),
      newFiles: codeChanges.files.filter((f) => f.status === "added").map((f) => f.path),
      deletedFiles: codeChanges.files.filter((f) => f.status === "deleted").map((f) => f.path),
      totalDiffLines: input.diff.split("\n").length,
      fileDiffs: new Map(
        codeChanges.files.map((f) => [f.path, f.diff ?? ""])
      )
    };
    const result = await runReviewPipeline({
      projectRoot,
      diff: diffInfo,
      commitMessage: input.commitMessage ?? "",
      flags: {
        comment: input.comment ?? false,
        ci: input.ci ?? false,
        deep: input.deep ?? false,
        noMechanical: input.noMechanical ?? false
      },
      ...input.repo != null ? { repo: input.repo } : {}
    });
    const sortedFindings = sortFindingsBySeverity(
      result.findings
    );
    if (input._skipPagination) {
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify({
              skipped: result.skipped,
              skipReason: result.skipReason,
              stoppedByMechanical: result.stoppedByMechanical,
              assessment: result.assessment,
              findings: sortedFindings,
              findingCount: sortedFindings.length,
              terminalOutput: result.terminalOutput,
              githubCommentCount: result.githubComments.length,
              exitCode: result.exitCode
            })
          }
        ]
      };
    }
    const paged = paginate(sortedFindings, input.offset ?? 0, input.limit ?? 20);
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(
            {
              skipped: result.skipped,
              skipReason: result.skipReason,
              stoppedByMechanical: result.stoppedByMechanical,
              assessment: result.assessment,
              findings: paged.items,
              findingCount: result.findings.length,
              pagination: paged.pagination,
              terminalOutput: result.terminalOutput,
              githubCommentCount: result.githubComments.length,
              exitCode: result.exitCode
            },
            null,
            2
          )
        }
      ],
      isError: false
    };
  } catch (error) {
    return {
      content: [
        {
          type: "text",
          text: `Error: ${error instanceof Error ? error.message : String(error)}`
        }
      ],
      isError: true
    };
  }
}

export {
  sortFindingsBySeverity,
  runCodeReviewDefinition,
  handleRunCodeReview
};
