import { useMutation } from "@tanstack/react-query";
import { apiRequest } from "./client";

// ── Scripts catalog ───────────────────────────────────────────────
// Surfaces the maintained `scripts/SCRIPTS.md` (single source of truth for
// every script under scripts/) read-only at /scripts. Edits go through
// git/Gitea, not the UI — the backend just reads the file at runtime.

export type ScriptsCatalog = {
  content: string;
  filename: string;
  bytes: number;
  last_modified: number;
  gitea_url: string;
  // #4 — basenames the UI may offer a "הרץ" button for (read-only allowlist,
  // enforced host-side). Optional so an older backend (pre-deploy) degrades to
  // "מקור"-only with no run buttons.
  runnable_scripts?: string[];
};

export function fetchScriptsCatalog(signal?: AbortSignal) {
  return apiRequest<ScriptsCatalog>("/api/scripts/catalog", { signal });
}

// ── Run a read-only script (#4) ───────────────────────────────────
// Proxies to the court-fetch host bridge; only allowlisted read-only scripts
// run, with a fixed safe argv. Exit code + captured output are relayed verbatim.
export type ScriptRunResult = {
  ok: boolean;
  exit_code: number;
  stdout: string;
  stderr: string;
};

export function useRunScript() {
  return useMutation({
    mutationFn: (name: string) =>
      apiRequest<ScriptRunResult>(
        `/api/scripts/${encodeURIComponent(name)}/run`,
        { method: "POST" },
      ),
  });
}
