import type { ExtensionAPI } from "@jaeswift/jae-coding-agent";
import { existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";

export default function (pi: ExtensionAPI) {
  pi.on("before_agent_start", async (_event, ctx) => {
    const rulesPath = join(ctx.cwd, ".jae", "rules.md");
    if (existsSync(rulesPath)) {
      const rules = readFileSync(rulesPath, "utf-8").trim();
      if (rules.length > 0) {
        return { systemPrompt: `\n\n# Project Rules (.jae/rules.md)\n\n${rules}` };
      }
    }
  });

  pi.registerCommand("rules", {
    description: "Show, create, or edit project rules (.jae/rules.md)",
    handler: async (args, ctx) => {
      const jaeDir = join(ctx.cwd, ".jae");
      const rulesPath = join(jaeDir, "rules.md");

      if (args.trim() === "init") {
        if (!existsSync(jaeDir)) mkdirSync(jaeDir, { recursive: true });
        if (!existsSync(rulesPath)) {
          writeFileSync(
            rulesPath,
            "# Project Rules\n\nAdd your project-specific rules here.\nThese will be injected into JAE's system prompt.\n",
            "utf-8",
          );
          ctx.ui.notify("Created .jae/rules.md - edit it to set project rules.", "info");
        } else {
          ctx.ui.notify(".jae/rules.md already exists.", "info");
        }
        return;
      }

      if (existsSync(rulesPath)) {
        const rules = readFileSync(rulesPath, "utf-8");
        ctx.ui.notify(
          `\u{1F4CB} Project Rules (${rules.length} chars):\n${rules.substring(0, 500)}${rules.length > 500 ? "..." : ""}`,
          "info",
        );
      } else {
        ctx.ui.notify("No .jae/rules.md found. Run /rules init to create one.", "warning");
      }
    },
  });
}
