const DEFAULT_TIMEOUT = 3e4;
const DEFAULT_RETRY_ATTEMPTS = 3;
const DEFAULT_RETRY_DELAY = 1e3;
class CloudApiClient {
  baseUrl;
  timeout;
  authToken;
  userAgent;
  retry;
  /**
   * Create a new CloudApiClient instance
   *
   * @param config - Client configuration
   */
  constructor(config) {
    this.baseUrl = config.baseUrl.replace(/\/$/, "");
    this.timeout = config.timeout || DEFAULT_TIMEOUT;
    this.authToken = config.authToken;
    this.userAgent = config.userAgent || "CCJK-Client/1.0";
    this.retry = config.retry || {
      maxAttempts: DEFAULT_RETRY_ATTEMPTS,
      delay: DEFAULT_RETRY_DELAY
    };
  }
  // ==========================================================================
  // Configuration Methods
  // ==========================================================================
  /**
   * Set authentication token
   *
   * @param token - Authentication token
   */
  setAuthToken(token) {
    this.authToken = token;
  }
  /**
   * Clear authentication token
   */
  clearAuthToken() {
    this.authToken = void 0;
  }
  /**
   * Get current base URL
   */
  getBaseUrl() {
    return this.baseUrl;
  }
  /**
   * Update base URL
   *
   * @param url - New base URL
   */
  setBaseUrl(url) {
    this.baseUrl = url.replace(/\/$/, "");
  }
  // ==========================================================================
  // Request Methods
  // ==========================================================================
  /**
   * Make an HTTP request to the cloud service
   *
   * @param path - API endpoint path (e.g., '/plugins/recommend')
   * @param options - Request options
   * @returns API response
   *
   * @example
   * ```typescript
   * const response = await client.request<{ data: string }>('/api/endpoint', {
   *   method: 'POST',
   *   body: { key: 'value' },
   *   timeout: 5000
   * })
   * ```
   */
  async request(path, options) {
    const maxAttempts = options.retry?.maxAttempts || this.retry.maxAttempts;
    const retryDelay = options.retry?.delay || this.retry.delay;
    let lastError = null;
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
      try {
        return await this.executeRequest(path, options);
      } catch (error) {
        lastError = error instanceof Error ? error : new Error(String(error));
        if (attempt === maxAttempts || this.isClientError(lastError)) {
          break;
        }
        await this.sleep(retryDelay * attempt);
      }
    }
    return {
      success: false,
      error: lastError?.message || "Request failed",
      code: "REQUEST_FAILED"
    };
  }
  /**
   * Execute a single HTTP request
   *
   * @private
   */
  async executeRequest(path, options) {
    const url = this.buildUrl(path, options.query);
    const timeout = options.timeout || this.timeout;
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    try {
      const headers = this.buildHeaders(options);
      const response = await fetch(url, {
        method: options.method,
        headers,
        body: options.body ? JSON.stringify(options.body) : void 0,
        signal: controller.signal
      });
      clearTimeout(timeoutId);
      const data = await response.json();
      if (!response.ok) {
        const errorMsg = typeof data.error === "object" && data.error !== null ? data.error.message || JSON.stringify(data.error) : data.error || `HTTP ${response.status}: ${response.statusText}`;
        const errorCode = typeof data.error === "object" && data.error !== null ? data.error.code || data.code : data.code;
        return {
          success: false,
          error: errorMsg,
          code: errorCode || `HTTP_${response.status}`
        };
      }
      return {
        ...data,
        success: true
      };
    } catch (error) {
      clearTimeout(timeoutId);
      if (error instanceof Error) {
        if (error.name === "AbortError") {
          return {
            success: false,
            error: "Request timeout",
            code: "TIMEOUT"
          };
        }
        return {
          success: false,
          error: error.message,
          code: "NETWORK_ERROR"
        };
      }
      return {
        success: false,
        error: String(error),
        code: "UNKNOWN_ERROR"
      };
    }
  }
  // ==========================================================================
  // Convenience Methods
  // ==========================================================================
  /**
   * Make a GET request
   *
   * @param path - API endpoint path
   * @param query - Query parameters
   * @param options - Additional request options
   * @returns API response
   */
  async get(path, query, options) {
    return this.request(path, {
      method: "GET",
      query,
      ...options
    });
  }
  /**
   * Make a POST request
   *
   * @param path - API endpoint path
   * @param body - Request body
   * @param options - Additional request options
   * @returns API response
   */
  async post(path, body, options) {
    return this.request(path, {
      method: "POST",
      body,
      ...options
    });
  }
  /**
   * Make a PUT request
   *
   * @param path - API endpoint path
   * @param body - Request body
   * @param options - Additional request options
   * @returns API response
   */
  async put(path, body, options) {
    return this.request(path, {
      method: "PUT",
      body,
      ...options
    });
  }
  /**
   * Make a DELETE request
   *
   * @param path - API endpoint path
   * @param options - Additional request options
   * @returns API response
   */
  async delete(path, options) {
    return this.request(path, {
      method: "DELETE",
      ...options
    });
  }
  // ==========================================================================
  // Helper Methods
  // ==========================================================================
  /**
   * Build full URL with query parameters
   *
   * @private
   */
  buildUrl(path, query) {
    const url = `${this.baseUrl}${path}`;
    if (!query || Object.keys(query).length === 0) {
      return url;
    }
    const params = new URLSearchParams();
    for (const [key, value] of Object.entries(query)) {
      params.append(key, String(value));
    }
    return `${url}?${params.toString()}`;
  }
  /**
   * Build request headers
   *
   * @private
   */
  buildHeaders(options) {
    const headers = {
      "Content-Type": "application/json",
      "User-Agent": this.userAgent,
      ...options.headers
    };
    const token = options.authToken || this.authToken;
    if (token) {
      headers.Authorization = `Bearer ${token}`;
    }
    return headers;
  }
  /**
   * Check if error is a client error (4xx)
   *
   * @private
   */
  isClientError(error) {
    return error.message.includes("HTTP 4");
  }
  /**
   * Sleep for specified milliseconds
   *
   * @private
   */
  sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
}
function createApiClient(config) {
  return new CloudApiClient(config);
}

export { CloudApiClient as C, createApiClient as c };
