import { isToolCallEventType, type ExtensionAPI } from "@mariozechner/pi-coding-agent";
import { buildDocyrusWebBrowserProtocolInstructions } from "../shared/docyrusWebBrowserProtocol";

const DOCYRUS_CHROME_COMMAND_PATTERN = /\bdocyrus\b(?:\s+-g|\s+--global)?\s+chrome\b/;
const DOCYRUS_CHROME_BLOCK_REASON =
  "Docyrus Server sessions must use the docyrus-web-browser preview tools instead of `docyrus chrome`.";

export default function docyrusWebBrowserExtension(pi: ExtensionAPI) {
  pi.on("before_agent_start", async(event) => {
    const protocolInstructions = buildDocyrusWebBrowserProtocolInstructions();
    return {
      systemPrompt: [event.systemPrompt, protocolInstructions].filter(Boolean).join("\n\n"),
    };
  });

  pi.on("tool_call", async(event) => {
    if (!isToolCallEventType("bash", event)) {
      return;
    }

    const command = typeof event.input.command === "string" ? event.input.command.trim() : "";
    if (!command || !DOCYRUS_CHROME_COMMAND_PATTERN.test(command)) {
      return;
    }

    return {
      block: true,
      reason: DOCYRUS_CHROME_BLOCK_REASON,
    };
  });
}
