/**
 * AIWG Server Plugin for OpenCode
 *
 * Integrates AIWG SDLC workflows with OpenCode's plugin hook system.
 * Injects AIWG context into the system prompt and enforces safety checks
 * on bash commands.
 *
 * Deploy to: .opencode/plugins/aiwg-hooks.ts
 * OpenCode auto-discovers all *.ts files in .opencode/plugins/
 *
 * Plugin API: @opencode-ai/plugin
 * Hook reference: https://opencode.ai/docs/plugins
 */

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

export const server: Plugin = async (input, _options) => {
  const { project, directory } = input

  return {
    /**
     * Inject AIWG context into every system prompt.
     * Adds the AIWG instructions file if present so agents are always
     * aware of the project's SDLC configuration without cluttering AGENTS.md.
     */
    "experimental.chat.system.transform": async (_input, output) => {
      // Inject AIWG instructions if the file exists
      const aiwgInstructions = `${directory}/.aiwg/instructions.md`
      try {
        const { readFile } = await import("fs/promises")
        const content = await readFile(aiwgInstructions, "utf8")
        output.system.push(content.trim())
      } catch {
        // File not present — skip silently
      }
    },

    /**
     * Intercept bash executions to enforce AIWG safety policy.
     * Denies known destructive patterns regardless of agent permission config.
     */
    "tool.execute.before": async (event_input, output) => {
      if (event_input.tool !== "bash") return

      const command: string = output.args?.command ?? ""

      const destructive = [
        /rm\s+-rf\s+\//,
        /git\s+push\s+--force\b(?!\s*--no-verify)/,
        /git\s+reset\s+--hard\s+HEAD~[2-9]/,
        /DROP\s+DATABASE/i,
        /TRUNCATE\s+TABLE/i,
      ]

      for (const pattern of destructive) {
        if (pattern.test(command)) {
          // Escalate to ask — overrides allow to require explicit confirmation
          output.args = {
            ...output.args,
            _aiwg_safety_flag: `destructive pattern detected: ${command.slice(0, 80)}`,
          }
          break
        }
      }
    },

    /**
     * Inject AIWG environment variables into every shell execution.
     * Makes AIWG_PROJECT_DIR available to scripts without manual config.
     */
    "shell.env": async (_input, output) => {
      output.env["AIWG_PROJECT_DIR"] = directory
      output.env["AIWG_PROJECT_NAME"] = project.git?.repo ?? ""
    },
  }
}

const plugin: PluginModule = { id: "aiwg-hooks", server }
export default plugin
