'use strict';

var fs4 = require('fs');
var path3 = require('path');
require('child_process');
require('util');

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

var fs4__default = /*#__PURE__*/_interopDefault(fs4);
var path3__default = /*#__PURE__*/_interopDefault(path3);

// src/features/gen-storybook/infrastructure/runtime.ts
function normalizePromptPathInput(value) {
  let normalized = value.trim();
  while (normalized.length >= 2 && (normalized.startsWith("`") && normalized.endsWith("`") || normalized.startsWith('"') && normalized.endsWith('"') || normalized.startsWith("'") && normalized.endsWith("'"))) {
    normalized = normalized.slice(1, -1).trim();
  }
  return normalized;
}

// src/features/gen-storybook/infrastructure/runtime.ts
var SUPPORTED_COMPONENT_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".jsx", ".ts", ".tsx"]);
var STORYBOOK_RESPONSE_FILE_SECTION_PATTERN = /^##\s+파일 내용\(자동 저장용\)\s*$/;
var STORYBOOK_RESPONSE_FILE_HEADER_PATTERN = /^-\s+(.+?)\s*$/;
var STORY_FILE_PATTERN = /\.stories\.(tsx|jsx|ts|js)$/;
var STATIC_TITLE_PATTERN = /\btitle\s*:\s*(['"`])(.+?)\1/;
var STORY_EXPORT_PATTERN = /export\s+const\s+([A-Za-z0-9_]+)/g;
var DISALLOWED_SAMPLE_CODE_PATTERNS = [/\?raw\b/, /raw-loader!/];
function resolveStoryFilePath(sourceFilePath) {
  const parsedPath = path3__default.default.parse(sourceFilePath);
  return path3__default.default.join(parsedPath.dir, `${parsedPath.name}.stories.tsx`);
}
function isPathInsideDirectory(directoryPath, targetPath) {
  const relativePath = path3__default.default.relative(directoryPath, targetPath);
  return relativePath !== "" && !relativePath.startsWith("..") && !path3__default.default.isAbsolute(relativePath);
}
function resolveGenStorybookSource(rootDir, sourceAddress) {
  const trimmedSourceAddress = normalizePromptPathInput(sourceAddress);
  if (!trimmedSourceAddress) {
    return {
      accessible: false,
      notes: ["\uB300\uC0C1 \uD30C\uC77C \uACBD\uB85C\uAC00 \uBE44\uC5B4 \uC788\uC2B5\uB2C8\uB2E4."],
      originalValue: sourceAddress,
      resolvedValue: "",
      sourceFilePath: "",
      storyDirectoryPath: "",
      storyFileExists: false,
      storyFilePath: ""
    };
  }
  if (/^https?:\/\//i.test(trimmedSourceAddress)) {
    return {
      accessible: false,
      notes: ["`/gen-storybook` \uB294 \uB85C\uCEEC \uCEF4\uD3EC\uB10C\uD2B8 \uD30C\uC77C \uACBD\uB85C\uB9CC \uC9C0\uC6D0\uD569\uB2C8\uB2E4. URL\uC740 \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4."],
      originalValue: sourceAddress,
      resolvedValue: trimmedSourceAddress,
      sourceFilePath: "",
      storyDirectoryPath: "",
      storyFileExists: false,
      storyFilePath: ""
    };
  }
  const sourceFilePath = path3__default.default.resolve(rootDir, trimmedSourceAddress);
  if (!fs4__default.default.existsSync(sourceFilePath)) {
    return {
      accessible: false,
      notes: [`\uB300\uC0C1 \uD30C\uC77C\uC774 \uC874\uC7AC\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4: ${sourceFilePath}`],
      originalValue: sourceAddress,
      resolvedValue: sourceFilePath,
      sourceFilePath: "",
      storyDirectoryPath: "",
      storyFileExists: false,
      storyFilePath: ""
    };
  }
  const stat = fs4__default.default.statSync(sourceFilePath);
  if (!stat.isFile()) {
    return {
      accessible: false,
      notes: [`\uB300\uC0C1 \uACBD\uB85C\uAC00 \uD30C\uC77C\uC774 \uC544\uB2D9\uB2C8\uB2E4: ${sourceFilePath}`],
      originalValue: sourceAddress,
      resolvedValue: sourceFilePath,
      sourceFilePath: "",
      storyDirectoryPath: "",
      storyFileExists: false,
      storyFilePath: ""
    };
  }
  const extension = path3__default.default.extname(sourceFilePath);
  if (!SUPPORTED_COMPONENT_EXTENSIONS.has(extension)) {
    return {
      accessible: false,
      notes: [`\uC9C0\uC6D0\uD558\uC9C0 \uC54A\uB294 \uD30C\uC77C \uD655\uC7A5\uC790\uC785\uB2C8\uB2E4: ${extension || "(\uC5C6\uC74C)"}`],
      originalValue: sourceAddress,
      resolvedValue: sourceFilePath,
      sourceFilePath: "",
      storyDirectoryPath: "",
      storyFileExists: false,
      storyFilePath: ""
    };
  }
  if (STORY_FILE_PATTERN.test(sourceFilePath)) {
    return {
      accessible: false,
      notes: ["\uC785\uB825 \uD30C\uC77C\uC774 \uC774\uBBF8 Storybook \uD30C\uC77C\uC785\uB2C8\uB2E4. \uCEF4\uD3EC\uB10C\uD2B8 \uC6D0\uBCF8 \uD30C\uC77C\uC744 \uC9C0\uC815\uD574\uC57C \uD569\uB2C8\uB2E4."],
      originalValue: sourceAddress,
      resolvedValue: sourceFilePath,
      sourceFilePath: "",
      storyDirectoryPath: "",
      storyFileExists: false,
      storyFilePath: ""
    };
  }
  try {
    fs4__default.default.accessSync(sourceFilePath, fs4__default.default.constants.R_OK);
  } catch {
    return {
      accessible: false,
      notes: [`\uB300\uC0C1 \uD30C\uC77C\uC744 \uC77D\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${sourceFilePath}`],
      originalValue: sourceAddress,
      resolvedValue: sourceFilePath,
      sourceFilePath: "",
      storyDirectoryPath: "",
      storyFileExists: false,
      storyFilePath: ""
    };
  }
  const storyFilePath = resolveStoryFilePath(sourceFilePath);
  return {
    accessible: true,
    notes: ["\uB300\uC0C1 \uCEF4\uD3EC\uB10C\uD2B8 \uD30C\uC77C\uC744 \uC77D\uC744 \uC218 \uC788\uC2B5\uB2C8\uB2E4. \uB3D9\uC77C \uD3F4\uB354\uC758 `*.stories.tsx` \uD30C\uC77C\uC744 \uC0DD\uC131\uD558\uAC70\uB098 \uAC31\uC2E0\uD569\uB2C8\uB2E4."],
    originalValue: sourceAddress,
    resolvedValue: sourceFilePath,
    sourceFilePath,
    storyDirectoryPath: path3__default.default.dirname(storyFilePath),
    storyFileExists: fs4__default.default.existsSync(storyFilePath),
    storyFilePath
  };
}
function extractResponseFileContent(lines, startIndex) {
  let index = startIndex;
  while (index < lines.length && !(lines[index] || "").trim().startsWith("```")) {
    index += 1;
  }
  if (index >= lines.length) {
    return {
      content: "",
      nextIndex: index
    };
  }
  index += 1;
  const contentLines = [];
  while (index < lines.length) {
    const line = lines[index] || "";
    if (line.trim().startsWith("```")) {
      index += 1;
      break;
    }
    contentLines.push(line);
    index += 1;
  }
  while (contentLines.length > 0 && contentLines.at(-1) === "") {
    contentLines.pop();
  }
  return {
    content: contentLines.join("\n"),
    nextIndex: index
  };
}
function resolveStorybookResponseFilePath(rootDir, outputDirectory, rawFilePath) {
  const normalizedRawPath = rawFilePath.trim().replace(/^`|`$/g, "").trim();
  if (!normalizedRawPath) {
    return "";
  }
  const candidates = path3__default.default.isAbsolute(normalizedRawPath) ? [path3__default.default.normalize(normalizedRawPath)] : [path3__default.default.resolve(outputDirectory, normalizedRawPath), path3__default.default.resolve(rootDir, normalizedRawPath)];
  return candidates.find((candidatePath) => isPathInsideDirectory(outputDirectory, candidatePath)) || "";
}
function normalizeStoryRelativePath(outputDirectory, absolutePath) {
  return path3__default.default.relative(outputDirectory, absolutePath).split(path3__default.default.sep).join("/");
}
function materializeGenStorybookResponseFiles(options) {
  const lines = options.responseText.split(/\r?\n/);
  const sectionStartIndex = lines.findIndex((line) => STORYBOOK_RESPONSE_FILE_SECTION_PATTERN.test(line));
  if (sectionStartIndex < 0) {
    return {
      detectedSection: false,
      parsedFiles: [],
      writtenFiles: []
    };
  }
  const parsedFiles = [];
  const writtenFiles = [];
  let index = sectionStartIndex + 1;
  while (index < lines.length) {
    const headerLine = lines[index] || "";
    const headerMatch = headerLine.match(STORYBOOK_RESPONSE_FILE_HEADER_PATTERN);
    if (!headerMatch) {
      index += 1;
      continue;
    }
    const absolutePath = resolveStorybookResponseFilePath(options.rootDir, options.outputDirectory, headerMatch[1] || "");
    if (!absolutePath) {
      index += 1;
      continue;
    }
    const { content, nextIndex } = extractResponseFileContent(lines, index + 1);
    const relativePath = normalizeStoryRelativePath(options.outputDirectory, absolutePath);
    parsedFiles.push(relativePath);
    if (content) {
      fs4__default.default.mkdirSync(path3__default.default.dirname(absolutePath), { recursive: true });
      fs4__default.default.writeFileSync(absolutePath, content, "utf8");
      writtenFiles.push(relativePath);
    }
    index = nextIndex;
  }
  return {
    detectedSection: true,
    parsedFiles: parsedFiles.sort((left, right) => left.localeCompare(right)),
    writtenFiles: writtenFiles.sort((left, right) => left.localeCompare(right))
  };
}
function extractStoryExportNames(storyFilePath) {
  const content = fs4__default.default.readFileSync(storyFilePath, "utf8");
  const exportNames = /* @__PURE__ */ new Set();
  let match = STORY_EXPORT_PATTERN.exec(content);
  while (match) {
    if (match[1]) {
      exportNames.add(match[1]);
    }
    match = STORY_EXPORT_PATTERN.exec(content);
  }
  STORY_EXPORT_PATTERN.lastIndex = 0;
  return [...exportNames];
}
function validateGeneratedStorybookFile(options) {
  const normalizedStoryFilePath = path3__default.default.normalize(options.expectedStoryFilePath);
  const storyFileName = path3__default.default.basename(normalizedStoryFilePath);
  const errors = [];
  if (!options.parsedFiles.includes(storyFileName)) {
    errors.push(`\uC790\uB3D9 \uC800\uC7A5 \uC751\uB2F5\uC5D0 \uB300\uC0C1 story \uD30C\uC77C \`${storyFileName}\` \uC774 \uD3EC\uD568\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.`);
  }
  if (options.parsedFiles.some((filePath) => filePath !== storyFileName)) {
    errors.push(`\uC790\uB3D9 \uC800\uC7A5 \uC751\uB2F5\uC5D0\uB294 \uB300\uC0C1 story \uD30C\uC77C \uD558\uB098\uB9CC \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4. \uD604\uC7AC=${options.parsedFiles.map((filePath) => `\`${filePath}\``).join(", ")}`);
  }
  if (!options.writtenFiles.includes(storyFileName)) {
    errors.push(`story \uD30C\uC77C\uC774 \uC2E4\uC81C\uB85C \uC800\uC7A5\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4: \`${storyFileName}\``);
  }
  if (!fs4__default.default.existsSync(normalizedStoryFilePath)) {
    errors.push(`\uC0DD\uC131\uB41C story \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: \`${normalizedStoryFilePath}\``);
  }
  if (errors.length > 0) {
    throw new Error(["gen-storybook \uACB0\uACFC \uAC80\uC99D\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.", ...errors.map((message) => `- ${message}`)].join("\n"));
  }
  const content = fs4__default.default.readFileSync(normalizedStoryFilePath, "utf8");
  const exportNames = extractStoryExportNames(normalizedStoryFilePath);
  const usageCaseStoryNames = exportNames.filter((exportName) => exportName !== "SampleCode");
  if (!STORY_FILE_PATTERN.test(normalizedStoryFilePath)) {
    errors.push(`story \uD30C\uC77C \uD655\uC7A5\uC790\uAC00 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4: \`${normalizedStoryFilePath}\``);
  }
  if (!STATIC_TITLE_PATTERN.test(content)) {
    errors.push("Story meta\uC758 `title` \uC744 \uC815\uC801 \uBB38\uC790\uC5F4\uB85C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.");
  }
  if (!exportNames.includes("SampleCode")) {
    errors.push("`SampleCode` story export\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.");
  }
  if (usageCaseStoryNames.length === 0) {
    errors.push("\uC0AC\uC6A9\uCC98 \uB610\uB294 \uC0C1\uD0DC\uB97C \uBCF4\uC5EC\uC8FC\uB294 story export\uAC00 \uCD5C\uC18C 1\uAC1C \uC774\uC0C1 \uD544\uC694\uD569\uB2C8\uB2E4.");
  }
  if (DISALLOWED_SAMPLE_CODE_PATTERNS.some((pattern) => pattern.test(content))) {
    errors.push("`SampleCode` \uB610\uB294 story \uD30C\uC77C\uC5D0\uC11C raw import \uACC4\uC5F4(`?raw`, `raw-loader!`) \uC0AC\uC6A9\uC774 \uAC10\uC9C0\uB418\uC5C8\uC2B5\uB2C8\uB2E4.");
  }
  if (errors.length > 0) {
    throw new Error(["gen-storybook \uACB0\uACFC \uAC80\uC99D\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.", ...errors.map((message) => `- ${message}`)].join("\n"));
  }
  return {
    exportNames,
    storyFilePath: normalizedStoryFilePath,
    usageCaseStoryNames
  };
}

exports.materializeGenStorybookResponseFiles = materializeGenStorybookResponseFiles;
exports.resolveGenStorybookSource = resolveGenStorybookSource;
exports.validateGeneratedStorybookFile = validateGeneratedStorybookFile;
