"use strict";

const fs = require("fs");
const path = require("path");

function generateLocalPaths({ projectDir, primaryPath, additionalRepos = [] }) {
  const claudeDir = path.join(projectDir, ".claude");
  fs.mkdirSync(claudeDir, { recursive: true });

  const lines = [
    "# Project Paths (Machine-Local)",
    "",
    "| Repository | Description | Absolute Path |",
    "| --- | --- | --- |",
    `| PRIMARY_PATH | Primary repo root | ${primaryPath} |`,
  ];

  for (const repo of additionalRepos) {
    lines.push(`| ${repo.name} | ${repo.description} | ${repo.path} |`);
  }

  lines.push("");
  const content = lines.join("\n");
  const filePath = path.join(claudeDir, "project-paths.local.md");
  fs.writeFileSync(filePath, content, "utf-8");
  return content;
}

const GITIGNORE_RULE = ".claude/project-paths.local.md";

function amendGitignore({ projectDir }) {
  const gitignorePath = path.join(projectDir, ".gitignore");
  let content = "";
  if (fs.existsSync(gitignorePath)) {
    content = fs.readFileSync(gitignorePath, "utf-8");
  }
  if (content.split("\n").some((line) => line.trim() === GITIGNORE_RULE)) {
    return;
  }
  const separator = content.length > 0 && !content.endsWith("\n") ? "\n" : "";
  content += separator + GITIGNORE_RULE + "\n";
  fs.writeFileSync(gitignorePath, content, "utf-8");
}

module.exports = { generateLocalPaths, amendGitignore };
