import type { Plugin } from "@opencode-ai/plugin"

const SOURCE_EXTENSIONS = [".lua", ".json"]

function isSourcePath(value: unknown) {
  return typeof value === "string" && SOURCE_EXTENSIONS.some((extension) => value.endsWith(extension))
}

function patchTouchesSource(value: unknown) {
  if (typeof value !== "string") return false
  for (const line of value.split("\n")) {
    if (!line.startsWith("*** Update File: ") && !line.startsWith("*** Add File: ")) continue
    if (isSourcePath(line.slice(line.indexOf(": ") + 2).trim())) return true
  }
  return false
}

function toolTouchesSource(args: Record<string, unknown>) {
  return (
    isSourcePath(args.filePath) ||
    isSourcePath(args.path) ||
    isSourcePath(args.target) ||
    patchTouchesSource(args.patchText) ||
    patchTouchesSource(args.patch)
  )
}

export const FixOnPackageSourceEdit: Plugin = async ({ $ }) => {
  let running = false

  return {
    "tool.execute.after": async (_input, output) => {
      if (running) return
      const args = output.args
      if (!args || typeof args !== "object" || !toolTouchesSource(args as Record<string, unknown>)) return

      running = true
      try {
        await $`just fix`
      } finally {
        running = false
      }
    },
  }
}
