import { execSync } from 'node:child_process';

// src/platform/core/git-helpers.ts
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;
  }
}

// src/features/commit/domain/workspace.ts
function getCommitUntrackedFilePaths(snapshot) {
  return snapshot.statusLines.map((line) => line.trim()).filter((line) => line.startsWith("?? ")).map((line) => line.slice(3).trim()).filter(Boolean);
}

// src/features/commit/infrastructure/workspace.ts
function captureCommitWorkspaceSnapshot(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 buildCommitPromptDiffMarkdown(rootDir, snapshot) {
  let trackedDiff = "";
  try {
    trackedDiff = runGitCommand(rootDir, "git diff HEAD --stat --patch -- .");
  } catch {
    try {
      trackedDiff = runGitCommand(rootDir, "git diff --stat --patch -- .");
    } catch {
      trackedDiff = "";
    }
  }
  const untrackedFilePaths = getCommitUntrackedFilePaths(snapshot);
  return [
    "# Commit Diff",
    "",
    "## git status --short -- .",
    "",
    "```text",
    snapshot.statusLines.join("\n") || "(\uC5C6\uC74C)",
    "```",
    trackedDiff.trim() ? ["", "## git diff HEAD --stat --patch -- .", "", "```diff", trackedDiff, "```"].join("\n") : "",
    untrackedFilePaths.length > 0 ? ["", "## untracked files", "", ...untrackedFilePaths.map((filePath) => `- ${filePath}`)].join("\n") : ""
  ].filter(Boolean).join("\n");
}

export { buildCommitPromptDiffMarkdown, captureCommitWorkspaceSnapshot };
