import fs from 'node:fs';
import path from 'node:path';

// src/features/minify-md/infrastructure/runtime.ts
var IGNORED_DIRECTORY_NAMES = /* @__PURE__ */ new Set([".git", ".ju-hong-e", "node_modules"]);
var MINIFIED_MARKDOWN_START = "[[MINIFIED_MD_START]]";
var MINIFIED_MARKDOWN_END = "[[MINIFIED_MD_END]]";
var MINIFY_LOG_START = "[[MINIFY_LOG_START]]";
var MINIFY_LOG_END = "[[MINIFY_LOG_END]]";
function isSourceMarkdownFileName(fileName) {
  const lowerName = fileName.toLowerCase();
  return lowerName.endsWith(".md") && !lowerName.endsWith(".min.md") && !lowerName.endsWith(".min-log.md");
}
function resolveMdMinifyInput(rootDir, input) {
  const resolvedPath = path.isAbsolute(input) ? path.normalize(input) : path.resolve(rootDir, input);
  const notes = [`- \uC785\uB825\uAC12: \`${input}\``, `- \uD574\uC11D \uACBD\uB85C: \`${resolvedPath}\``];
  if (!fs.existsSync(resolvedPath)) {
    notes.push("- \uC0C1\uD0DC: \uACBD\uB85C\uAC00 \uC874\uC7AC\uD558\uC9C0 \uC54A\uC74C");
    return {
      accessible: false,
      inputPath: resolvedPath,
      inputType: "directory",
      directoryPath: resolvedPath,
      notes
    };
  }
  const stat = fs.statSync(resolvedPath);
  if (stat.isDirectory()) {
    notes.push("- \uC785\uB825 \uC885\uB958: \uB514\uB809\uD130\uB9AC");
    notes.push("- \uC0C1\uD0DC: \uC811\uADFC \uAC00\uB2A5");
    return {
      accessible: true,
      inputPath: resolvedPath,
      inputType: "directory",
      directoryPath: resolvedPath,
      notes
    };
  }
  if (!stat.isFile()) {
    notes.push("- \uC0C1\uD0DC: \uD30C\uC77C\uC774\uB098 \uB514\uB809\uD130\uB9AC\uAC00 \uC544\uB2D8");
    return {
      accessible: false,
      inputPath: resolvedPath,
      inputType: "file",
      directoryPath: path.dirname(resolvedPath),
      notes
    };
  }
  notes.push("- \uC785\uB825 \uC885\uB958: \uD30C\uC77C");
  if (!isSourceMarkdownFileName(path.basename(resolvedPath))) {
    notes.push("- \uC0C1\uD0DC: \uC6D0\uBCF8 markdown \uD30C\uC77C(.md)\uB9CC \uC785\uB825 \uAC00\uB2A5\uD558\uBA70, .min.md/.min-log.md \uC0B0\uCD9C\uBB3C\uC740 \uC81C\uC678\uB428");
    return {
      accessible: false,
      filePath: resolvedPath,
      inputPath: resolvedPath,
      inputType: "file",
      directoryPath: path.dirname(resolvedPath),
      notes
    };
  }
  notes.push("- \uC0C1\uD0DC: \uC811\uADFC \uAC00\uB2A5");
  return {
    accessible: true,
    filePath: resolvedPath,
    inputPath: resolvedPath,
    inputType: "file",
    directoryPath: path.dirname(resolvedPath),
    notes
  };
}
function collectMarkdownFiles(directoryPath) {
  const entries = fs.readdirSync(directoryPath, { withFileTypes: true });
  const collected = [];
  entries.forEach((entry) => {
    const nextPath = path.join(directoryPath, entry.name);
    if (entry.isDirectory()) {
      if (!IGNORED_DIRECTORY_NAMES.has(entry.name)) {
        collected.push(...collectMarkdownFiles(nextPath));
      }
      return;
    }
    if (!entry.isFile()) {
      return;
    }
    if (!isSourceMarkdownFileName(entry.name)) {
      return;
    }
    collected.push(nextPath);
  });
  return collected.sort((left, right) => left.localeCompare(right));
}
function collectMarkdownFilesFromInput(inputResolution) {
  if (!inputResolution.accessible) {
    return [];
  }
  if (inputResolution.inputType === "file") {
    return inputResolution.filePath ? [inputResolution.filePath] : [];
  }
  return collectMarkdownFiles(inputResolution.directoryPath);
}
function resolveAvailableMinifyOutputPaths(sourceFilePath) {
  const directoryPath = path.dirname(sourceFilePath);
  const extension = path.extname(sourceFilePath);
  const baseName = path.basename(sourceFilePath, extension);
  const buildOutputPaths = (suffix = "") => ({
    minifiedFilePath: path.join(directoryPath, `${baseName}${suffix}.min.md`),
    minifyLogFilePath: path.join(directoryPath, `${baseName}${suffix}.min-log.md`)
  });
  let outputPaths = buildOutputPaths();
  if (!fs.existsSync(outputPaths.minifiedFilePath) && !fs.existsSync(outputPaths.minifyLogFilePath)) {
    return outputPaths;
  }
  let index = 1;
  while (fs.existsSync(outputPaths.minifiedFilePath) || fs.existsSync(outputPaths.minifyLogFilePath)) {
    outputPaths = buildOutputPaths(`_${index}`);
    index += 1;
  }
  return outputPaths;
}
function unwrapResponseFence(responseText) {
  const trimmed = responseText.trim();
  if (!trimmed) {
    return "";
  }
  const fencedMatch = trimmed.match(/^```(?:md|markdown|text)?\s*([\s\S]*?)\s*```$/i);
  return (fencedMatch?.[1] ?? trimmed).trim();
}
function extractMarkedSection(content, startMarker, endMarker) {
  const startIndex = content.indexOf(startMarker);
  const endIndex = content.indexOf(endMarker);
  if (startIndex < 0 || endIndex < 0 || endIndex <= startIndex) {
    return "";
  }
  return content.slice(startIndex + startMarker.length, endIndex).trim();
}
function parseLegacyMdMinifyResponse(content) {
  const duplicateHeadingIndex = content.indexOf("## \uC911\uBCF5\uD655\uC778\uD544\uC694");
  const removeHeadingIndex = content.indexOf("## \uC81C\uAC70\uD655\uC778\uD544\uC694");
  const logStartIndex = [duplicateHeadingIndex, removeHeadingIndex].filter((index) => index >= 0).sort((left, right) => left - right)[0];
  if (logStartIndex === void 0) {
    return {
      minifiedMarkdown: content.trim(),
      minifyLogMarkdown: ["## \uC911\uBCF5\uD655\uC778\uD544\uC694", "", "- \uC5C6\uC74C", "", "## \uC81C\uAC70\uD655\uC778\uD544\uC694", "", "- \uC5C6\uC74C"].join("\n")
    };
  }
  const minifiedMarkdown = content.slice(0, logStartIndex).trim();
  const minifyLogMarkdown = content.slice(logStartIndex).trim();
  return {
    minifiedMarkdown,
    minifyLogMarkdown
  };
}
function parseMdMinifyResponse(responseText) {
  const normalizedResponse = unwrapResponseFence(responseText);
  if (!normalizedResponse) {
    return {
      minifiedMarkdown: "",
      minifyLogMarkdown: ""
    };
  }
  const minifiedMarkdown = extractMarkedSection(normalizedResponse, MINIFIED_MARKDOWN_START, MINIFIED_MARKDOWN_END);
  const minifyLogMarkdown = extractMarkedSection(normalizedResponse, MINIFY_LOG_START, MINIFY_LOG_END);
  if (minifiedMarkdown || minifyLogMarkdown) {
    return {
      minifiedMarkdown: minifiedMarkdown.trim(),
      minifyLogMarkdown: minifyLogMarkdown.trim()
    };
  }
  return parseLegacyMdMinifyResponse(normalizedResponse);
}
function writeMinifiedMarkdownFile(filePath, content) {
  fs.writeFileSync(filePath, `${content.trim()}
`, "utf8");
}
function writeMinifyLogMarkdownFile(filePath, content) {
  fs.writeFileSync(filePath, `${content.trim()}
`, "utf8");
}

export { collectMarkdownFiles, collectMarkdownFilesFromInput, parseMdMinifyResponse, resolveAvailableMinifyOutputPaths, resolveMdMinifyInput, writeMinifiedMarkdownFile, writeMinifyLogMarkdownFile };
