/**
 * Vigil runtime integration for Node.js 18+ / TypeScript. No dependencies.
 * Set VIGIL_API_KEY (the per-agent key identifies the agent).
 * Fails closed: stops on block, timeouts, network/HTTP errors and invalid verdicts.
 * Check planned tools BEFORE invoking them — recording a trace cannot undo an action.
 */
export type Decision = "allow" | "flag" | "block";

export interface Violation { message?: string; severity?: string; guardrail?: string; [k: string]: unknown }

export interface Verdict {
  decision: Decision;
  violations?: Violation[];
  redacted_input?: string | null;
  redacted_output?: string | null;
  [k: string]: unknown;
}

export interface ToolCall { name: string; arguments?: unknown; result?: unknown; status?: string; latency_ms?: number }

export class SecurityViolationError extends Error {
  constructor(message: string, readonly verdict?: Verdict) {
    super(message);
    this.name = "SecurityViolationError";
  }
}

export interface VigilClientOptions { baseUrl?: string; timeoutMs?: number; fetch?: typeof fetch }

export class VigilClient {
  private readonly baseUrl: string;
  private readonly timeoutMs: number;
  private readonly fetchImpl: typeof fetch;

  constructor(private readonly apiKey: string, options: VigilClientOptions = {}) {
    if (!apiKey || !apiKey.trim()) throw new Error("A Vigil agent API key is required");
    this.baseUrl = (options.baseUrl ?? "https://vigiltrism.ai/api/public/v1").replace(/\/+$/, "");
    this.timeoutMs = options.timeoutMs ?? 10_000;
    this.fetchImpl = options.fetch ?? fetch;
  }

  /** Pre-flight: scan the prompt and retrieved documents before calling the model. */
  preFlightCheck(input: string, retrievedDocs: string[] = [], traceId?: string): Promise<Verdict> {
    return this.post("scan", {
      input,
      retrieved_documents: retrievedDocs.map((content) => ({ content })),
      ...(traceId ? { trace_id: traceId } : {}),
    }, 200);
  }

  /** Post-execution: check the model output and tool calls before releasing them. */
  postExecutionCheck(input: string, output: string, toolCalls: ToolCall[] = [], traceId?: string): Promise<Verdict> {
    return this.post("executions", {
      input,
      output,
      tool_calls: toolCalls,
      ...(traceId ? { trace_id: traceId } : {}),
    }, 201);
  }

  private async post(path: string, payload: Record<string, unknown>, expected: number): Promise<Verdict> {
    let result: unknown;
    try {
      const res = await this.fetchImpl(`${this.baseUrl}/${path}`, {
        method: "POST",
        redirect: "error",
        headers: { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json" },
        body: JSON.stringify(payload),
        signal: AbortSignal.timeout(this.timeoutMs),
      });
      // Do not echo response bodies: they may contain sensitive data.
      if (res.status !== expected) throw new SecurityViolationError(`Vigil check failed (HTTP ${res.status})`);
      result = await res.json();
    } catch (error) {
      if (error instanceof SecurityViolationError) throw error;
      throw new SecurityViolationError("Vigil check unavailable or invalid; execution halted");
    }
    const verdict = result as Verdict;
    if (!verdict || typeof verdict !== "object" || !["allow", "flag", "block"].includes(verdict.decision)) {
      throw new SecurityViolationError("Invalid Vigil decision; execution halted");
    }
    if (verdict.decision === "block") {
      const reasons = Array.isArray(verdict.violations)
        ? verdict.violations.map((v) => v?.message).filter((m): m is string => typeof m === "string")
        : [];
      throw new SecurityViolationError(`Execution halted by Vigil: ${reasons.join("; ") || "Security policy violation"}`, verdict);
    }
    return verdict;
  }
}

const TOOL_ARG_RULES: Array<[string, RegExp]> = [
  ["Destructive shell command", /\b(rm\s+-[a-z]*[rf][a-z]*\s+[/~*]|mkfs(\.\w+)?\s|dd\s+if=|shutdown\s+-[hr]|chmod\s+-R\s+777\s+\/)/i],
  ["Remote download piped to a shell", /\b(curl|wget)\b[^|\n]{0,300}\|\s*(sudo\s+)?(ba|z)?sh\b/i],
  ["Destructive SQL statement", /\b(drop\s+(table|database|schema)|truncate\s+table|alter\s+table\s+\S+\s+drop)\b|\bxp_cmdshell\b/i],
  ["SQL injection pattern", /('|")\s*(or|and)\s+('|")?\d+('|")?\s*=\s*('|")?\d+|;\s*--|\bunion\s+(all\s+)?select\b/i],
  ["Path traversal or sensitive file", /(\.\.[/\\]){2,}|%2e%2e[/\\%]|\/etc\/(passwd|shadow|sudoers)|~\/\.ssh|\.aws\/credentials|(^|[/\\])\.env\b/i],
  ["Cloud metadata endpoint", /169\.254\.169\.254|metadata\.google\.internal|100\.100\.100\.200/i],
];

/**
 * Local, deterministic check BEFORE a tool runs (no network). Throws on dangerous
 * arguments. `allowedHosts`: if given, URLs to any other host are blocked.
 */
export function validateToolArguments(tool: string, args: unknown, allowedHosts?: string[]): void {
  const text = (typeof args === "string" ? args : JSON.stringify(args ?? "")).slice(0, 50_000);
  const hits = TOOL_ARG_RULES.filter(([, re]) => re.test(text)).map(([label]) => label);
  if (allowedHosts) {
    for (const m of text.matchAll(/\bhttps?:\/\/([^\s/:?#"'\\)]+)/gi)) {
      const host = m[1]!.toLowerCase();
      if (!allowedHosts.some((a) => host === a.toLowerCase() || host.endsWith("." + a.toLowerCase()))) hits.push(`Host not allowlisted: ${host}`);
    }
  }
  if (hits.length) throw new SecurityViolationError(`Tool '${tool}' blocked: ${[...new Set(hits)].join("; ")}`);
}

/* Example usage:
const vigil = new VigilClient(process.env.VIGIL_API_KEY!);
try {
  const pre = await vigil.preFlightCheck(userPrompt, ragDocs);
  const safeInput = pre.redacted_input ?? userPrompt;
  const answer = await callYourModel(safeInput);
  validateToolArguments("fetch", plannedArgs, ["api.example.com"]); // before any tool runs
  const post = await vigil.postExecutionCheck(safeInput, answer);
  release(post.redacted_output ?? answer);
} catch (e) {
  if (e instanceof SecurityViolationError) halt(e.message); else throw e;
}
*/
