// tokenlean plugin for Open Code
// Generated by: tl-hook install opencode
//
// Auto-wraps wasteful bash commands with token-efficient alternatives.
// Build/test commands → tl-run (compresses output ~65%)
// curl requests → tl-browse (clean markdown output)

const BUILD_TEST_PATTERNS = [
  /\b(npm|yarn|pnpm|bun)\s+(test|run\s+test|run\s+build|run\s+lint)/,
  /\bnode\s+--test\b/,
  /\b(cargo|go)\s+(test|build|check|clippy)\b/,
  /\b(make|cmake)\b/,
  /\b(pytest|python\s+-m\s+(pytest|unittest))\b/,
  /\b(mvn|gradle)\s+(test|build|compile)\b/,
  /\b(dotnet)\s+(test|build)\b/,
  /\b(mix)\s+(test|compile)\b/,
  /\b(bundle\s+exec\s+r(spec|ake))\b/,
  /\btsc\b/,
  /\beslint\b/,
  /\bprettier\b/,
];

function extractHttpUrl(command) {
  return String(command || "").match(/https?:\/\/[^\s"'<>|)]+/)?.[0] || null;
}

function isLocalOrPrivateHost(hostname) {
  const host = String(hostname || "").toLowerCase();
  if (host === "localhost" || host === "0.0.0.0" || host === "::1") return true;
  if (/^127\./.test(host)) return true;
  if (/^10\./.test(host)) return true;
  if (/^192\.168\./.test(host)) return true;
  if (/^172\.(1[6-9]|2\d|3[01])\./.test(host)) return true;
  return false;
}

function isApiLikeUrl(url) {
  try {
    const parsed = new URL(url);
    const host = parsed.hostname.toLowerCase();
    const path = parsed.pathname.toLowerCase();
    return isLocalOrPrivateHost(host)
      || host.startsWith("api.")
      || path === "/api"
      || path.startsWith("/api/")
      || path === "/graphql"
      || path.startsWith("/graphql/");
  } catch {
    return true;
  }
}

function hasApiCurlOptions(command) {
  return /(?:^|\s)(?:-[XHI]|--request|--header|--data(?:-[\w-]+)?|-d|--include|--head)\b/i.test(command);
}

function shouldSuggestBrowseForCurl(command) {
  if (!/^\s*curl\s/.test(command)) return false;
  if (hasApiCurlOptions(command)) return false;

  const url = extractHttpUrl(command);
  return Boolean(url && !isApiLikeUrl(url));
}

export const TokenleanPlugin = async () => ({
  "tool.execute.before": async (input, output) => {
    if (input.tool !== "bash") return;
    const cmd = output.args.command || "";
    if (/\btl-/.test(cmd)) return;

    // Build/test commands → wrap with tl-run
    if (BUILD_TEST_PATTERNS.some((p) => p.test(cmd))) {
      output.args.command = `tl-run "${cmd.replace(/"/g, '\\"')}"`;
      return;
    }

    // curl (non-API) → replace with tl-browse
    if (shouldSuggestBrowseForCurl(cmd)) {
      output.args.command = `tl-browse "${extractHttpUrl(cmd)}"`;
    }
  },
});
