// src/client/tql-client.ts
class TQLError extends Error {
  status;
  constructor(message, status) {
    super(message);
    this.status = status;
    this.name = "TQLError";
  }
}

class TQLClient {
  baseUrl;
  fetch;
  apiKey;
  constructor(baseUrlOrOptions) {
    if (typeof baseUrlOrOptions === "string") {
      this.baseUrl = baseUrlOrOptions.replace(/\/$/, "");
      this.fetch = globalThis.fetch;
      this.apiKey = undefined;
    } else {
      this.baseUrl = baseUrlOrOptions.baseUrl.replace(/\/$/, "");
      this.fetch = baseUrlOrOptions.fetch ?? globalThis.fetch;
      this.apiKey = baseUrlOrOptions.apiKey;
    }
  }
  async req(method, path, body) {
    const headers = {};
    if (body !== undefined)
      headers["Content-Type"] = "application/json";
    if (this.apiKey)
      headers["Authorization"] = `Bearer ${this.apiKey}`;
    const res = await this.fetch(`${this.baseUrl}${path}`, {
      method,
      headers,
      body: body !== undefined ? JSON.stringify(body) : undefined
    });
    const data = await res.json();
    if (!res.ok) {
      throw new TQLError(data.error ?? `HTTP ${res.status}`, res.status);
    }
    return data;
  }
  async provision(adminKey, label) {
    const headers = {
      "Content-Type": "application/json",
      Authorization: `Bearer ${adminKey}`
    };
    const res = await this.fetch(`${this.baseUrl}/instances`, {
      method: "POST",
      headers,
      body: JSON.stringify({ label })
    });
    const data = await res.json();
    if (!res.ok) {
      throw new TQLError(data.error ?? `HTTP ${res.status}`, res.status);
    }
    return data;
  }
  health() {
    return this.req("GET", "/health");
  }
  stats() {
    return this.req("GET", "/stats");
  }
  catalog() {
    return this.req("GET", "/catalog");
  }
  listNodes() {
    return this.req("GET", "/nodes");
  }
  createNode(id, data, type = "default") {
    return this.req("POST", "/nodes", { id, data, type });
  }
  getNode(id) {
    return this.req("GET", `/nodes/${encodeURIComponent(id)}`);
  }
  updateNode(id, data, type = "default") {
    return this.req("PUT", `/nodes/${encodeURIComponent(id)}`, { data, type });
  }
  deleteNode(id) {
    return this.req("DELETE", `/nodes/${encodeURIComponent(id)}`);
  }
  listLinks() {
    return this.req("GET", "/links");
  }
  createLink(source, relation, target) {
    return this.req("POST", "/links", { source, target, relation });
  }
  query(q) {
    return this.req("POST", "/query", { q });
  }
  queryNatural(q, context) {
    return this.req("POST", "/query", { q, natural: true, context });
  }
  exportWorkspace() {
    return this.req("GET", "/workspace");
  }
  bootWorkspace(config) {
    return this.req("POST", "/workspace", config);
  }
  checkpoint() {
    return this.req("POST", "/workspace/checkpoint");
  }
}
export {
  TQLError,
  TQLClient
};
