import { Plugin } from "@opencode/plugin"
import { readFile } from "node:fs/promises"
import { join } from "node:path"
import { insertGuidelines } from "./insert"

export default Plugin.define({
  id: "guidelines",
  async setup(ctx) {
    const root = ctx.location.project?.canonical ?? ctx.location.directory

    const rulesPath = join(root, "RULES.md")

    await ctx.session.hook("context", async (event) => {
      let rules: string
      try {
        rules = (await readFile(rulesPath, "utf8")).trim()
      } catch {
        return
      }
      insertGuidelines(event.system, rules, rulesPath)
    })
  },
})
