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

// ctx-wire OpenCode plugin - rewrites shell commands through ctx-wire so their
// output reaches the model with noise filtered and secrets scrubbed.
//
// Thin delegating plugin: all rewrite logic lives in `ctx-wire rewrite` (the
// single source of truth). Do not edit this file to change rules.
// Requires ctx-wire on PATH.

export const CtxWireOpenCodePlugin: Plugin = async ({ $ }) => {
  try {
    await $`which ctx-wire`.quiet()
  } catch {
    console.warn("[ctx-wire] binary not found in PATH - plugin disabled")
    return {}
  }

  return {
    "tool.execute.before": async (input, output) => {
      const tool = String(input?.tool ?? "").toLowerCase()
      if (tool !== "bash" && tool !== "shell") return
      const args = output?.args
      if (!args || typeof args !== "object") return

      const command = (args as Record<string, unknown>).command
      if (typeof command !== "string" || !command) return

      try {
        const result = await $`ctx-wire rewrite --agent opencode ${command}`.quiet().nothrow()
        const rewritten = String(result.stdout).trim()
        if (rewritten && rewritten !== command) {
          ;(args as Record<string, unknown>).command = rewritten
        }
      } catch {
        // ctx-wire rewrite failed - pass the command through unchanged.
      }
    },
  }
}
