'use strict';

var fs = require('fs');
var path = require('path');
require('crypto');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var fs__default = /*#__PURE__*/_interopDefault(fs);
var path__default = /*#__PURE__*/_interopDefault(path);

// src/features/gen-html/infrastructure/runtime.ts
var GEN_HTML_RESPONSE_FILE_HEADER_PATTERN = /^\s*-\s+(.+)$/;
var GEN_HTML_RESPONSE_FILE_SECTION_PATTERN = /파일 내용.*저장/;
function normalizeOutputRelativePath(outputDirectory, filePath) {
  return path__default.default.relative(outputDirectory, filePath).split(path__default.default.sep).join("/");
}
function isPathInsideDirectory(directoryPath, filePath) {
  const relativePath = path__default.default.relative(directoryPath, filePath);
  return relativePath !== "" && relativePath !== ".." && !relativePath.startsWith(`..${path__default.default.sep}`) && !path__default.default.isAbsolute(relativePath);
}
function resolveGenHtmlResponseFilePath(rootDir, outputDirectory, rawFilePath) {
  const normalizedRawPath = rawFilePath.trim().replace(/^`|`$/g, "").replace(/:$/, "");
  if (!normalizedRawPath) {
    return "";
  }
  const candidatePaths = path__default.default.isAbsolute(normalizedRawPath) ? [path__default.default.normalize(normalizedRawPath)] : [path__default.default.resolve(rootDir, normalizedRawPath), path__default.default.resolve(outputDirectory, normalizedRawPath)];
  const resolvedPath = candidatePaths.find((candidatePath) => isPathInsideDirectory(outputDirectory, candidatePath));
  return resolvedPath ? path__default.default.normalize(resolvedPath) : "";
}
function extractGenHtmlResponseFileContent(lines, startIndex) {
  const contentLines = [];
  let index = startIndex;
  const firstLine = lines[index] || "";
  const fenceMatch = firstLine.match(/^(\s*)```/);
  if (fenceMatch) {
    const fenceIndent = fenceMatch[1] || "";
    index += 1;
    while (index < lines.length) {
      const line = lines[index] || "";
      if (line.startsWith(`${fenceIndent}\`\`\``)) {
        index += 1;
        break;
      }
      contentLines.push(line.startsWith(fenceIndent) ? line.slice(fenceIndent.length) : line);
      index += 1;
    }
  } else {
    while (index < lines.length) {
      const line = lines[index] || "";
      if (GEN_HTML_RESPONSE_FILE_HEADER_PATTERN.test(line)) {
        break;
      }
      if (!line) {
        contentLines.push("");
        index += 1;
        continue;
      }
      if (line.startsWith("  ")) {
        contentLines.push(line.slice(2));
        index += 1;
        continue;
      }
      if (line.startsWith("	")) {
        contentLines.push(line.slice(1));
        index += 1;
        continue;
      }
      break;
    }
  }
  while (contentLines.length > 0 && contentLines.at(-1) === "") {
    contentLines.pop();
  }
  return {
    content: contentLines.join("\n"),
    nextIndex: index
  };
}
function parseGenHtmlResponseFiles(rootDir, outputDirectory, responseText) {
  const lines = responseText.split(/\r?\n/);
  const sectionStartIndex = lines.findIndex((line) => GEN_HTML_RESPONSE_FILE_SECTION_PATTERN.test(line));
  if (sectionStartIndex < 0) {
    return [];
  }
  const files = [];
  let index = sectionStartIndex + 1;
  while (index < lines.length) {
    const line = lines[index] || "";
    const headerMatch = line.match(GEN_HTML_RESPONSE_FILE_HEADER_PATTERN);
    if (!headerMatch) {
      index += 1;
      continue;
    }
    const absolutePath = resolveGenHtmlResponseFilePath(rootDir, outputDirectory, headerMatch[1] || "");
    if (!absolutePath) {
      index += 1;
      continue;
    }
    const { content, nextIndex } = extractGenHtmlResponseFileContent(lines, index + 1);
    if (content) {
      files.push({
        absolutePath,
        content,
        relativePath: normalizeOutputRelativePath(outputDirectory, absolutePath)
      });
    }
    index = nextIndex;
  }
  return files;
}
var STORY_FILE_PATTERN = /\.stories\.[cm]?[jt]sx?$/i;
var STORY_META_TITLE_PATTERN = /(\btitle\s*:\s*)(['"`])([^'"`]+)\2/;
function isGenHtmlStoryFilePath(filePath) {
  return STORY_FILE_PATTERN.test(filePath);
}
function normalizeStoryTitlePrefix(prefix) {
  return prefix.trim().replace(/^\/+|\/+$/g, "");
}
function ensureStoryTitlePrefix(title, prefix) {
  const normalizedPrefix = normalizeStoryTitlePrefix(prefix);
  if (!normalizedPrefix) {
    return title.trim();
  }
  const normalizedTitle = title.trim().replace(/^\/+/, "");
  return normalizedTitle.startsWith(`${normalizedPrefix}/`) ? normalizedTitle : `${normalizedPrefix}/${normalizedTitle}`;
}
function applyStorybookTitlePrefixToStorySource(content, prefix) {
  const normalizedPrefix = normalizeStoryTitlePrefix(prefix);
  if (!normalizedPrefix) {
    return content;
  }
  const match = content.match(STORY_META_TITLE_PATTERN);
  if (!match) {
    return content;
  }
  const nextTitle = ensureStoryTitlePrefix(match[3] || "", normalizedPrefix);
  return content.replace(STORY_META_TITLE_PATTERN, (_fullMatch, titlePrefix, quoteCharacter) => {
    return `${titlePrefix}${quoteCharacter}${nextTitle}${quoteCharacter}`;
  });
}

// src/features/gen-html/infrastructure/runtime.ts
function listOutputFiles(outputDirectory) {
  if (!fs__default.default.existsSync(outputDirectory) || !fs__default.default.statSync(outputDirectory).isDirectory()) {
    return [];
  }
  const files = [];
  const visitDirectory = (directoryPath) => {
    const entries = fs__default.default.readdirSync(directoryPath, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
    for (const entry of entries) {
      const entryPath = path__default.default.join(directoryPath, entry.name);
      if (entry.isDirectory()) {
        visitDirectory(entryPath);
        continue;
      }
      if (entry.isFile()) {
        files.push(normalizeOutputRelativePath(outputDirectory, entryPath));
      }
    }
  };
  visitDirectory(outputDirectory);
  return files.sort((left, right) => left.localeCompare(right));
}
function materializeGenHtmlResponseFiles(options) {
  const parsedFiles = parseGenHtmlResponseFiles(options.rootDir, options.outputDirectory, options.responseText);
  const writtenFiles = /* @__PURE__ */ new Set();
  for (const file of parsedFiles) {
    fs__default.default.mkdirSync(path__default.default.dirname(file.absolutePath), { recursive: true });
    fs__default.default.writeFileSync(file.absolutePath, file.content, "utf8");
    writtenFiles.add(file.relativePath);
  }
  return [...writtenFiles].sort((left, right) => left.localeCompare(right));
}
function applyStorybookTitlePrefixToOutputDirectory(options) {
  if (!options.prefix.trim()) {
    return [];
  }
  const updatedFiles = [];
  for (const relativeFilePath of listOutputFiles(options.outputDirectory).filter((filePath) => isGenHtmlStoryFilePath(filePath))) {
    const filePath = path__default.default.join(options.outputDirectory, relativeFilePath);
    const content = fs__default.default.readFileSync(filePath, "utf8");
    const nextContent = applyStorybookTitlePrefixToStorySource(content, options.prefix);
    if (nextContent !== content) {
      fs__default.default.writeFileSync(filePath, nextContent, "utf8");
      updatedFiles.push(relativeFilePath);
    }
  }
  return updatedFiles.sort((left, right) => left.localeCompare(right));
}
function isGenHtmlPreviewDirectoryCandidate(outputDirectory) {
  return listOutputFiles(outputDirectory).some((filePath) => isGenHtmlStoryFilePath(filePath));
}

exports.applyStorybookTitlePrefixToOutputDirectory = applyStorybookTitlePrefixToOutputDirectory;
exports.isGenHtmlPreviewDirectoryCandidate = isGenHtmlPreviewDirectoryCandidate;
exports.materializeGenHtmlResponseFiles = materializeGenHtmlResponseFiles;
