import { inspect } from 'node:util';
import fs from 'node:fs';
import path from 'node:path';

// src/platform/core/string-helpers.ts
function safeExcerpt(content, limit = 3e3) {
  if (!content) {
    return "";
  }
  if (content.length <= limit) {
    return content;
  }
  return `${content.slice(0, limit)}
... (truncated ${content.length - limit} chars)`;
}
function stringifyUnknown(value) {
  if (value === void 0 || value === null) {
    return "";
  }
  if (typeof value === "string") {
    return value;
  }
  if (Buffer.isBuffer(value)) {
    return value.toString("utf8");
  }
  if (value instanceof Error) {
    return value.stack || value.message;
  }
  return inspect(value, { depth: 6, breakLength: 120 });
}
function getErrorSummary(error) {
  if (error instanceof Error) {
    return `${error.name}: ${error.message}`;
  }
  return stringifyUnknown(error) || "Unknown error";
}

// 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 getAvailableFilePath(directory, baseName, extension) {
  const first = path.join(directory, `${baseName}${extension}`);
  if (!fs.existsSync(first)) {
    return first;
  }
  let next = first;
  let count = 1;
  while (fs.existsSync(next)) {
    next = path.join(directory, `${baseName}-${count}${extension}`);
    if (!fs.existsSync(next)) {
      break;
    }
    count += 1;
  }
  return next;
}
function renderSections(sections = []) {
  if (sections.length === 0) {
    return "";
  }
  return sections.map((section) => `
## ${section.heading}

${section.markdown}
`).join("\n");
}
function serializeError(error) {
  const serialized = {
    summary: getErrorSummary(error)
  };
  if (error instanceof Error) {
    serialized.name = error.name;
    serialized.message = error.message;
    serialized.stack = error.stack;
  } else {
    serialized.value = stringifyUnknown(error);
  }
  if (error && typeof error === "object") {
    const errorLike = error;
    ["code", "errno", "syscall", "path", "cmd", "status", "signal"].forEach((key) => {
      if (errorLike[key] !== void 0) {
        serialized[key] = errorLike[key];
      }
    });
    const stdout = stringifyUnknown(errorLike.stdout);
    if (stdout) {
      serialized.stdout = stdout;
    }
    const stderr = stringifyUnknown(errorLike.stderr);
    if (stderr) {
      serialized.stderr = stderr;
    }
  }
  return serialized;
}
function writeErrorReport(paths, error, options) {
  const filePath = getAvailableFilePath(paths.errorDir, `${getFileTimestamp()}-error`, ".md");
  const serializedError = serializeError(error);
  const traceMessages = options.traceMessages ?? [];
  const markdown = `# Error Report

- \uC2DC\uAC01: ${getHumanReadableNow()}
- scope: \`${options.scope}\`
- \uC791\uC5C5 \uACBD\uB85C: \`${paths.rootDir}\`
- \uC2E4\uD589 \uC778\uC790: \`${JSON.stringify(options.args ?? process.argv.slice(2))}\`

## Summary

${serializedError.summary || "Unknown error"}

## Error

\`\`\`json
${JSON.stringify(serializedError, null, 2)}
\`\`\`

## Trace

\`\`\`json
${JSON.stringify(traceMessages, null, 2)}
\`\`\`${renderSections(options.extraSections)}
`;
  fs.writeFileSync(filePath, markdown, "utf8");
  return filePath;
}
var TRACE_MESSAGES = [];
function getTraceMessages() {
  return [...TRACE_MESSAGES];
}

// 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/gen-html-multiple/infrastructure/error-report.ts
var COMPONENT_LOG_REPORT_LIMIT = 4e4;
function writeGenHtmlMultipleComponentErrorReport(options) {
  const reportPath = writeErrorReport(options.paths, options.error, {
    args: [
      "/gen-html-multiple",
      `component=${options.component.componentName}`,
      `output=${options.component.outputPath}`
    ],
    extraSections: [
      {
        heading: "Current Service",
        markdown: `\`${options.service}\``
      },
      {
        heading: "Gen HTML Multiple Component",
        markdown: [
          formatGenHtmlComponentInputMarkdown({
            componentName: options.component.componentName,
            references: options.component.references
          }),
          `- id: \`${options.component.id}\``,
          `- status: \`${options.component.status}\``,
          `- outputPath: \`${options.component.outputPath}\``,
          `- queuedAt: \`${options.component.queuedAt || "(\uC5C6\uC74C)"}\``,
          `- startedAt: \`${options.component.startedAt || "(\uC5C6\uC74C)"}\``,
          `- refreshStartedAt: \`${options.component.refreshStartedAt || "(\uC5C6\uC74C)"}\``
        ].join("\n")
      },
      {
        heading: "Runtime Log",
        markdown: options.component.log ? ["```text", safeExcerpt(options.component.log, COMPONENT_LOG_REPORT_LIMIT), "```"].join("\n") : "(\uC5C6\uC74C)"
      }
    ],
    scope: "gen-html-multiple:component",
    traceMessages: getTraceMessages()
  });
  options.trace(
    "gen-html-multiple:component:error-report",
    `${options.component.componentName} ${getErrorSummary(options.error)} report=${reportPath}`
  );
  return reportPath;
}

export { writeGenHtmlMultipleComponentErrorReport };
