import fs3 from 'node:fs';
import { execFile, execSync } from 'node:child_process';
import path from 'node:path';
import { promisify } from 'node:util';

// src/features/token-optimizer/infrastructure/config.ts
var DEFAULT_TOKEN_OPTIMIZER_STATE = {
  enabled: false
};
globalThis.__JU_HONG_E_TOKEN_OPTIMIZER_STATE__ ?? (globalThis.__JU_HONG_E_TOKEN_OPTIMIZER_STATE__ = {
  ...DEFAULT_TOKEN_OPTIMIZER_STATE
});
function runGitCommand(rootDir, command) {
  return execSync(command, {
    cwd: rootDir,
    encoding: "utf8",
    maxBuffer: 1024 * 1024 * 20,
    stdio: ["ignore", "pipe", "pipe"]
  }).trim();
}
function isGitRepository(rootDir) {
  try {
    runGitCommand(rootDir, "git rev-parse --show-toplevel");
    return true;
  } catch {
    return false;
  }
}
function captureWorkspaceSnapshot(rootDir) {
  if (!isGitRepository(rootDir)) {
    return {
      available: false,
      branch: "",
      diffNameStatus: "",
      diffStat: "",
      gitRoot: "",
      note: "\uD604\uC7AC \uC791\uC5C5 \uACBD\uB85C\uAC00 Git \uC800\uC7A5\uC18C\uAC00 \uC544\uB2D9\uB2C8\uB2E4.",
      recentCommits: [],
      statusLines: []
    };
  }
  const gitRoot = runGitCommand(rootDir, "git rev-parse --show-toplevel");
  const branch = runGitCommand(rootDir, "git branch --show-current");
  const statusOutput = runGitCommand(rootDir, "git status --short");
  const diffStat = runGitCommand(rootDir, "git diff --stat");
  const diffNameStatus = runGitCommand(rootDir, "git diff --name-status");
  const recentCommits = runGitCommand(rootDir, "git log --oneline -5");
  return {
    available: true,
    branch,
    diffNameStatus,
    diffStat,
    gitRoot,
    note: "",
    recentCommits: recentCommits ? recentCommits.split("\n").filter(Boolean) : [],
    statusLines: statusOutput ? statusOutput.split("\n").filter(Boolean) : []
  };
}
function statusLineToPath(statusLine) {
  const normalized = statusLine.trim();
  if (!normalized) {
    return "";
  }
  const pathValue = normalized.slice(3).split(" -> ").pop();
  return pathValue?.trim() || normalized;
}
function diffWorkspaceSnapshots(before, after) {
  const beforeSet = new Set(before.statusLines);
  const afterSet = new Set(after.statusLines);
  const beforeOnly = before.statusLines.filter((line) => !afterSet.has(line));
  const afterOnly = after.statusLines.filter((line) => !beforeSet.has(line));
  const touchedFiles = Array.from(
    new Set([...beforeOnly.map(statusLineToPath), ...afterOnly.map(statusLineToPath)].filter(Boolean))
  );
  return {
    afterOnly,
    beforeOnly,
    touchedFiles
  };
}
function formatCodeBlock(content, language = "") {
  return `\`\`\`${language}
${content || "(\uC5C6\uC74C)"}
\`\`\``;
}
function formatWorkspaceSnapshot(snapshot) {
  if (!snapshot.available) {
    return snapshot.note;
  }
  return [
    `- Git Root: \`${snapshot.gitRoot}\``,
    `- Branch: \`${snapshot.branch || "(detached)"}\``,
    "",
    "### git status --short",
    formatCodeBlock(snapshot.statusLines.join("\n")),
    "",
    "### git diff --stat",
    formatCodeBlock(snapshot.diffStat),
    "",
    "### git diff --name-status",
    formatCodeBlock(snapshot.diffNameStatus),
    "",
    "### \uCD5C\uADFC \uCEE4\uBC0B",
    formatCodeBlock(snapshot.recentCommits.join("\n"))
  ].join("\n");
}
function formatWorkspaceDelta(delta) {
  return [
    "### \uC0C8\uB85C \uAC10\uC9C0\uB41C \uC0C1\uD0DC",
    formatCodeBlock(delta.afterOnly.join("\n")),
    "",
    "### \uC0AC\uB77C\uC9C4 \uC774\uC804 \uC0C1\uD0DC",
    formatCodeBlock(delta.beforeOnly.join("\n")),
    "",
    "### \uC601\uD5A5 \uD30C\uC77C",
    formatCodeBlock(delta.touchedFiles.join("\n"))
  ].join("\n");
}

// src/platform/core/timestamp-helpers.ts
function padTimestampPart(value) {
  return String(value).padStart(2, "0");
}
function getTimestampParts(now = /* @__PURE__ */ new Date()) {
  return {
    year: now.getFullYear(),
    month: padTimestampPart(now.getMonth() + 1),
    day: padTimestampPart(now.getDate()),
    hour: padTimestampPart(now.getHours()),
    minute: padTimestampPart(now.getMinutes()),
    second: padTimestampPart(now.getSeconds())
  };
}
function getFileTimestamp(now = /* @__PURE__ */ new Date()) {
  const { year, month, day, hour, minute, second } = getTimestampParts(now);
  return `${year}-${month}-${day}_${hour}-${minute}-${second}`;
}
function getHumanReadableNow(now = /* @__PURE__ */ new Date()) {
  const { year, month, day, hour, minute, second } = getTimestampParts(now);
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
function appendConversationHistory(paths, entry) {
  const normalizedEntry = {
    ...entry,
    summary: entry.summary.trim() || entry.title.trim(),
    timestamp: entry.timestamp || getHumanReadableNow(),
    title: entry.title.trim()
  };
  fs3.appendFileSync(paths.conversationHistoryPath, `${JSON.stringify(normalizedEntry)}
`, "utf8");
  return normalizedEntry;
}
function getAvailableFilePath(directory, baseName, extension) {
  const first = path.join(directory, `${baseName}${extension}`);
  if (!fs3.existsSync(first)) {
    return first;
  }
  let next = first;
  let count = 1;
  while (fs3.existsSync(next)) {
    next = path.join(directory, `${baseName}-${count}${extension}`);
    if (!fs3.existsSync(next)) {
      break;
    }
    count += 1;
  }
  return next;
}
function appendHistoryIndex(paths, summary, relativeFilePath) {
  const line = `- ${getHumanReadableNow()} | ${summary} | file: \`${relativeFilePath}\`
`;
  fs3.appendFileSync(paths.historyIndexPath, line, "utf8");
}
function renderSections(sections = []) {
  if (sections.length === 0) {
    return "";
  }
  return sections.map((section) => `
## ${section.heading}

${section.markdown}
`).join("\n");
}
function writeTurnHistory(paths, record) {
  const baseName = `${getFileTimestamp()}-${record.scope}`;
  const filePath = getAvailableFilePath(paths.turnsDir, baseName, ".md");
  const markdown = `# ${record.title}

- \uC2DC\uAC01: ${getHumanReadableNow()}
- scope: \`${record.scope}\`
- service: \`${record.service}\`
- skipped: \`${record.skipped}\`

## \uC0AC\uC6A9\uC790 \uC785\uB825

${formatCodeBlock(record.input)}

## AI \uC751\uB2F5

${record.output || "(\uC751\uB2F5 \uC5C6\uC74C)"}

## \uCD5C\uADFC \uD788\uC2A4\uD1A0\uB9AC \uC8FC\uC785

${formatCodeBlock(record.historyContext)}

## \uC2E4\uD589 \uBA85\uB839\uC5B4 \uBBF8\uB9AC\uBCF4\uAE30

${formatCodeBlock(record.previewCommand, "sh")}

## \uC791\uC5C5 \uC804 \uC6CC\uD06C\uC2A4\uD398\uC774\uC2A4

${formatWorkspaceSnapshot(record.workspaceBefore)}

## \uC791\uC5C5 \uD6C4 \uC6CC\uD06C\uC2A4\uD398\uC774\uC2A4

${formatWorkspaceSnapshot(record.workspaceAfter)}

## \uC6CC\uD06C\uC2A4\uD398\uC774\uC2A4 \uBCC0\uD654

${formatWorkspaceDelta(record.workspaceDelta)}${renderSections(record.extraSections)}
`;
  fs3.writeFileSync(filePath, markdown, "utf8");
  appendHistoryIndex(paths, `${record.scope} | ${record.service} | ${record.title}`, path.relative(paths.rootDir, filePath));
  return filePath;
}
promisify(execFile);

// src/platform/request-security/registry.ts
var securityRegistryState = globalThis.__JUHONG_E_SECURITY_REGISTRY__ ?? (globalThis.__JUHONG_E_SECURITY_REGISTRY__ = {
  patternRules: /* @__PURE__ */ new Map(),
  validatorRules: /* @__PURE__ */ new Map()
});
securityRegistryState.patternRules;
securityRegistryState.validatorRules;

// src/platform/ai-services/stream-output.ts
var DEFAULT_STREAM_OUTPUT_STATE = {
  enabled: false
};
globalThis.__JU_HONG_E_STREAM_OUTPUT_STATE__ ?? (globalThis.__JU_HONG_E_STREAM_OUTPUT_STATE__ = {
  ...DEFAULT_STREAM_OUTPUT_STATE
});

// src/platform/actions/shared.ts
function finalizeAction(paths, context, result) {
  const extraSections = [...result.extraSections || [], ...buildPromptAuditSections(result.promptAudit)];
  const workspaceAfter = captureWorkspaceSnapshot(paths.rootDir);
  const workspaceDelta = diffWorkspaceSnapshots(context.workspaceBefore, workspaceAfter);
  const historyPath = writeTurnHistory(paths, {
    extraSections,
    historyContext: context.historyContext,
    input: result.input,
    output: result.output,
    previewCommand: result.previewCommand,
    scope: result.scope,
    service: result.service,
    skipped: result.skipped,
    title: result.title,
    workspaceAfter,
    workspaceBefore: context.workspaceBefore,
    workspaceDelta
  });
  appendConversationHistory(paths, {
    input: result.input,
    output: result.output,
    scope: result.scope,
    service: result.service,
    summary: result.summary,
    title: result.title
  });
  return {
    historyPath,
    previewCommand: result.previewCommand,
    scope: result.scope,
    service: result.service,
    skipped: result.skipped,
    summary: result.summary,
    title: result.title,
    traceMessages: []
  };
}
function formatAuditNumber(value) {
  return value.toLocaleString("ko-KR");
}
function buildPromptAuditSections(promptAudit) {
  if (!promptAudit) {
    return [];
  }
  return [
    {
      heading: "\uD504\uB86C\uD504\uD2B8 \uCD5C\uC801\uD654 \uC694\uC57D",
      markdown: [
        `- mode: \`${promptAudit.mode}\``,
        `- \uCD5C\uC801\uD654 \uC804 \uD504\uB86C\uD504\uD2B8 \uD06C\uAE30: \`${formatAuditNumber(promptAudit.originalBytes)} bytes\``,
        `- \uCD5C\uC801\uD654 \uD6C4 \uD504\uB86C\uD504\uD2B8 \uD06C\uAE30: \`${formatAuditNumber(promptAudit.optimizedBytes)} bytes\``,
        `- \uAC10\uC18C\uD55C \uD504\uB86C\uD504\uD2B8 \uD06C\uAE30: \`${formatAuditNumber(promptAudit.reducedBytes)} bytes\``,
        `- \uAC10\uC18C \uBE44\uC728: \`${promptAudit.reductionPercent}%\``,
        `- \uC608\uC0C1 \uD1A0\uD070(\uC804 -> \uD6C4): \`${formatAuditNumber(promptAudit.originalEstimatedTokens)} -> ${formatAuditNumber(promptAudit.optimizedEstimatedTokens)}\``,
        `- \uAC10\uC18C\uD55C \uC608\uC0C1 \uD1A0\uD070: \`${formatAuditNumber(promptAudit.reducedEstimatedTokens)}\``,
        `- \uC608\uC0C1 \uD1A0\uD070 \uAC10\uC18C \uBE44\uC728: \`${promptAudit.tokenReductionPercent}%\``
      ].join("\n")
    },
    {
      heading: "\uD504\uB86C\uD504\uD2B8 \uCD5C\uC801\uD654 \uC804",
      markdown: formatCodeBlock(promptAudit.originalPrompt)
    },
    {
      heading: "\uD504\uB86C\uD504\uD2B8 \uCD5C\uC801\uD654 \uD6C4",
      markdown: formatCodeBlock(promptAudit.optimizedPrompt)
    }
  ];
}
function formatDependencyMarkdown(dependencies) {
  const lines = Object.entries(dependencies).map(([name, version]) => `- ${name}: \`${version}\``);
  return lines.length > 0 ? lines.join("\n") : "- (\uC5C6\uC74C)";
}

// src/features/gen-html/domain/component-input.ts
function normalizeGenHtmlComponentName(componentName) {
  return componentName.trim();
}
function normalizeGenHtmlReferenceInput(reference) {
  return {
    description: reference.description.trim(),
    figmaAddress: reference.figmaAddress.trim()
  };
}
function normalizeGenHtmlComponentInput(component) {
  return {
    componentName: normalizeGenHtmlComponentName(component.componentName),
    references: component.references.map(normalizeGenHtmlReferenceInput).filter((reference) => Boolean(reference.figmaAddress))
  };
}
function formatGenHtmlComponentInputMarkdown(component) {
  const normalizedComponent = normalizeGenHtmlComponentInput(component);
  return [
    `- componentName: \`${normalizedComponent.componentName}\``,
    `- referenceCount: \`${normalizedComponent.references.length}\``,
    normalizedComponent.references.length > 0 ? normalizedComponent.references.map(
      (reference, index) => [
        `- [${index + 1}] figmaAddress: \`${reference.figmaAddress}\``,
        reference.description ? `  description: ${reference.description}` : "  description: (\uC5C6\uC74C)"
      ].join("\n")
    ).join("\n") : "- references: (\uC5C6\uC74C)"
  ].join("\n");
}

// src/features/mcp/infrastructure/runtime.ts
var MCP_SERVICE_ORDER = ["codex", "gemini", "claude"];

// src/features/gen-html/domain/storybook-mcp.ts
var STORYBOOK_MCP_SERVER_NAME = "storybook-mcp";
var STORYBOOK_MCP_SERVER_URL = "https://main--685dde4728854606b608af64.chromatic.com/mcp";
function createStorybookMcpServerInput() {
  return {
    name: STORYBOOK_MCP_SERVER_NAME,
    transport: "http",
    url: STORYBOOK_MCP_SERVER_URL
  };
}

// src/features/gen-html/application/storybook-mcp-report.ts
function sortServiceResults(serviceResults) {
  return [...serviceResults].sort(
    (left, right) => MCP_SERVICE_ORDER.indexOf(left.service) - MCP_SERVICE_ORDER.indexOf(right.service)
  );
}
function formatStorybookMcpServiceResultsMarkdown(serviceResults) {
  if (serviceResults.length === 0) {
    return "- \uAE30\uC874 \uC124\uC815\uC774 \uC788\uC5B4 \uC774\uBC88 \uC2E4\uD589\uC5D0\uC11C \uCD94\uAC00 \uB3D9\uAE30\uD654\uB294 \uC5C6\uC5C8\uC2B5\uB2C8\uB2E4.";
  }
  return sortServiceResults(serviceResults).map((result) => `- ${result.service}: \`${result.ok ? "\uC131\uACF5" : "\uC2E4\uD328"}${result.skipped ? " (\uC0DD\uB7B5)" : ""}\` - ${result.detail}`).join("\n");
}
function formatStorybookMcpHealthCheckMarkdown(healthCheck) {
  return [
    `- ${healthCheck.endpoint.label}: \`${healthCheck.endpoint.ok}\``,
    `- detail: ${healthCheck.endpoint.detail}`,
    "",
    "### \uC11C\uBE44\uC2A4\uBCC4 \uC124\uC815 \uC0C1\uD0DC",
    ...sortServiceResults(healthCheck.services).map(
      (result) => `- ${result.service}: \`${result.ok ? "\uC124\uC815\uB428" : "\uB204\uB77D\uB428"}\` - ${result.detail}`
    )
  ].join("\n");
}
function formatStorybookMcpEnsureResultMarkdown(ensureResult) {
  const desiredInput = createStorybookMcpServerInput();
  return [
    `- serverName: \`${desiredInput.name}\``,
    `- url: \`${"url" in desiredInput ? desiredInput.url : ""}\``,
    `- registrationCreated: \`${ensureResult.registrationCreated}\``,
    `- registrationUpdated: \`${ensureResult.registrationUpdated}\``,
    `- repaired: \`${ensureResult.repaired}\``,
    "",
    "### \uD5EC\uC2A4\uCCB4\uD06C",
    formatStorybookMcpHealthCheckMarkdown(ensureResult.healthCheck),
    "",
    "### \uC774\uBC88 \uC2E4\uD589\uC758 \uB3D9\uAE30\uD654 \uACB0\uACFC",
    formatStorybookMcpServiceResultsMarkdown(ensureResult.syncResults)
  ].join("\n");
}

// src/features/gen-html/application/finalize-record.ts
function formatParsedReferenceMarkdown(references) {
  return references.map(
    (reference, index) => [
      `### Reference ${index + 1}`,
      `- description: ${reference.description || "(\uC5C6\uC74C)"}`,
      `- figmaAddress: \`${reference.figmaAddress}\``,
      reference.figmaSource.fileKey ? `- fileKey: \`${reference.figmaSource.fileKey}\`` : "- fileKey: `(\uCD94\uCD9C \uC2E4\uD328)`",
      reference.figmaSource.branchKey ? `- branchKey: \`${reference.figmaSource.branchKey}\`` : "",
      reference.figmaSource.resolvedFileKey ? `- resolvedFileKey: \`${reference.figmaSource.resolvedFileKey}\`` : "",
      reference.figmaSource.nodeId ? `- nodeId: \`${reference.figmaSource.nodeId}\`` : "- nodeId: `(\uCD94\uCD9C \uC2E4\uD328)`",
      reference.figmaSource.normalizedNodeId ? `- normalizedNodeId: \`${reference.figmaSource.normalizedNodeId}\`` : "",
      reference.figmaSource.parseNotes.length > 0 ? `- parseNotes:
${reference.figmaSource.parseNotes.map((note) => `  - ${note}`).join("\n")}` : ""
    ].filter(Boolean).join("\n")
  ).join("\n\n");
}
function finalizeGenHtmlExecutionRecord(options, context, artifacts, preview) {
  options.status.step("\uC751\uB2F5\uACFC Storybook \uC774\uB825\uC744 \uC800\uC7A5\uD558\uB294 \uC911\uC785\uB2C8\uB2E4.");
  return finalizeAction(options.paths, context, {
    extraSections: [
      {
        heading: "Gen HTML \uC785\uB825",
        markdown: [
          formatGenHtmlComponentInputMarkdown(artifacts.component),
          `- outputPath: \`${artifacts.outputPath}\``,
          `- resolvedOutputDirectory: \`${artifacts.resolvedOutputDirectory}\``,
          "",
          formatParsedReferenceMarkdown(artifacts.parsedReferences)
        ].filter(Boolean).join("\n")
      },
      {
        heading: "\uB85C\uCEEC \uD504\uB9AC\uBDF0 \uC11C\uBC84",
        markdown: [
          `- packageJsonPath: \`${preview.localServerSetup.packageJsonPath}\``,
          `- dependencies:
${formatDependencyMarkdown(preview.localServerSetup.dependencies)}`,
          `- packageJsonChanged: \`${Boolean(preview.localServerSetup.packageJsonChanged)}\``,
          `- storybookConfigChanged: \`${Boolean(preview.localServerSetup.storybookConfigChanged)}\``,
          `- alreadyRunning: \`${preview.localServerRuntime.alreadyRunning}\``,
          `- skipped: \`${preview.localServerRuntime.skipped}\``,
          `- port: \`${preview.localServerRuntime.port}\``,
          `- baseUrl: \`${preview.localServerRuntime.baseUrl}\``,
          `- previewUrl: \`${preview.previewUrl}\``,
          `- previewStoryFound: \`${preview.previewStoryFound}\``,
          `- previewStoryId: \`${preview.previewStoryId || "(\uC5C6\uC74C)"}\``,
          `- previewOpened: \`${preview.previewOpened}\``,
          `- restartRequired: \`${preview.restartRequired}\``,
          `- logPath: \`${preview.localServerRuntime.logPath}\``,
          `- previewOpenSummary: ${preview.previewOpenSummary}`
        ].join("\n")
      },
      ...options.storybookMcpEnsureResult ? [
        {
          heading: "Storybook MCP \uBCF4\uC7A5 \uACB0\uACFC",
          markdown: formatStorybookMcpEnsureResultMarkdown(options.storybookMcpEnsureResult)
        }
      ] : [],
      {
        heading: "\uC0DD\uC131 \uACB0\uACFC \uC800\uC7A5",
        markdown: artifacts.generationSummary
      },
      {
        heading: "\uC0DD\uC131 \uC11C\uBE44\uC2A4 \uC751\uB2F5",
        markdown: artifacts.combinedStdout || "(\uC751\uB2F5 \uC5C6\uC74C)"
      },
      {
        heading: "\uC0DD\uC131 \uC11C\uBE44\uC2A4 stderr",
        markdown: artifacts.combinedStderr ? `\`\`\`
${artifacts.combinedStderr}
\`\`\`` : "(\uC5C6\uC74C)"
      },
      {
        heading: "\uC2E4\uD589\uB41C \uBA85\uB839",
        markdown: [
          "```sh",
          artifacts.combinedPreview || "(\uC5C6\uC74C)",
          "```"
        ].join("\n")
      }
    ],
    input: [
      "/gen-html",
      `component=${artifacts.component.componentName}`,
      ...artifacts.component.references.map((reference, index) => `reference${index + 1}=${reference.figmaAddress} | ${reference.description || "(\uC124\uBA85 \uC5C6\uC74C)"}`),
      `output=${artifacts.outputPath}`
    ].join("\n"),
    output: artifacts.combinedStdout,
    promptAudit: artifacts.promptAudit,
    previewCommand: artifacts.combinedPreview,
    scope: "gen-html",
    service: options.service,
    skipped: artifacts.skipped,
    summary: `gen-html \uC644\uB8CC: ${artifacts.component.componentName} -> ${artifacts.outputPath}`,
    title: `gen-html: ${artifacts.component.componentName}`
  });
}

export { finalizeGenHtmlExecutionRecord };
