#!/usr/bin/env node
"use strict";

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

const packageDir = path.resolve(__dirname, "..");
const initCwd = process.env.INIT_CWD ? path.resolve(process.env.INIT_CWD) : "";
const projectRoot = initCwd || path.resolve(packageDir, "..", "..", "..");
const knowledgeFileName = "BFRS_AGENTIC_COMPONENTS.md";
const referenceLine = `Use ${knowledgeFileName} for knowledge regarding the component library.`;

const src = path.join(packageDir, knowledgeFileName);
const dest = path.join(projectRoot, knowledgeFileName);
const agentFileGroups = [
  ["AGENTS.md", "agents.md"],
  ["CLAUDE.md", "claude.md"]
];

function sameRealPath(a, b) {
  try {
    return fs.realpathSync(a) === fs.realpathSync(b);
  } catch {
    return path.resolve(a) === path.resolve(b);
  }
}

const isInsideNodeModules = packageDir.split(path.sep).includes("node_modules");
const isConsumerLifecycle = initCwd && !sameRealPath(initCwd, packageDir);
if (!isInsideNodeModules && !isConsumerLifecycle) {
  process.exit(0);
}

if (!fs.existsSync(src)) {
  process.exit(0);
}

function ensureTrailingNewline(content) {
  return content.endsWith("\n") ? content : `${content}\n`;
}

function ensureReference(filePath) {
  if (!fs.existsSync(filePath)) {
    fs.writeFileSync(filePath, `${referenceLine}\n`, "utf8");
    return "created";
  }

  const existing = fs.readFileSync(filePath, "utf8");
  if (existing.includes(referenceLine)) {
    return "unchanged";
  }

  fs.writeFileSync(filePath, `${ensureTrailingNewline(existing)}\n${referenceLine}\n`, "utf8");
  return "updated";
}

function resolveAgentFile(fileNames) {
  const existingFileName = fileNames.find((fileName) => fs.existsSync(path.join(projectRoot, fileName)));
  return path.join(projectRoot, existingFileName || fileNames[0]);
}

try {
  fs.copyFileSync(src, dest);

  const results = agentFileGroups.map((fileNames) => {
    const filePath = resolveAgentFile(fileNames);
    return `${path.basename(filePath)}:${ensureReference(filePath)}`;
  });

  console.log(
    `[agentic-components] Installed ${knowledgeFileName} and updated agent references (${results.join(", ")}).`
  );
} catch (err) {
  // Never fail a consumer's install.
  console.warn("[agentic-components] Could not install agent context:", err.message);
}
