'use strict';

// src/features/commit/domain/draft.ts
function extractMarkdownSection(markdown, heading) {
  const escapedHeading = heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  const match = markdown.match(new RegExp(`^##\\s+${escapedHeading}\\s*$\\n+([\\s\\S]*?)(?=^##\\s+|\\Z)`, "m"));
  return match?.[1]?.trim() || "";
}
function normalizeInlineValue(value) {
  let normalized = value.trim();
  while (normalized.startsWith("`") && normalized.endsWith("`") || normalized.startsWith('"') && normalized.endsWith('"') || normalized.startsWith("'") && normalized.endsWith("'")) {
    normalized = normalized.slice(1, -1).trim();
  }
  if (normalized === "(\uC5C6\uC74C)") {
    return "";
  }
  return normalized.replace(/\s+/g, " ").trim();
}
function resolveCommitMessageDraft(rawOutput) {
  const statusLine = rawOutput.match(/^- 상태:\s*(.+)$/m)?.[1] || "";
  const commitMessageLine = rawOutput.match(/^- 제안 커밋 메시지:\s*(.+)$/m)?.[1] || rawOutput.match(/^- 사용한 커밋 메시지:\s*(.+)$/m)?.[1] || "";
  const message = normalizeInlineValue(commitMessageLine);
  const normalizedStatus = normalizeInlineValue(statusLine);
  const rationale = extractMarkdownSection(rawOutput, "\uD310\uB2E8 \uADFC\uAC70");
  if (message) {
    return {
      message,
      rationale,
      rawOutput,
      state: "generated"
    };
  }
  if (normalizedStatus.includes("\uBCC0\uACBD\uC5C6\uC74C")) {
    return {
      message: "",
      rationale,
      rawOutput,
      state: "no-change"
    };
  }
  return {
    message: "",
    rationale,
    rawOutput,
    state: "failed"
  };
}

exports.resolveCommitMessageDraft = resolveCommitMessageDraft;
