import { c as consola, o as ofetch } from './ccjk.CoCHVXl3.mjs';
import fs__default, { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
import path__default, { join, dirname } from 'node:path';
import { randomUUID } from 'node:crypto';
import { homedir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { CLOUD_ENDPOINTS } from '../chunks/constants.mjs';

const defaults = Object.freeze({
  ignoreUnknown: false,
  respectType: false,
  respectFunctionNames: false,
  respectFunctionProperties: false,
  unorderedObjects: true,
  unorderedArrays: false,
  unorderedSets: false,
  excludeKeys: void 0,
  excludeValues: void 0,
  replacer: void 0
});
function objectHash(object, options) {
  if (options) {
    options = { ...defaults, ...options };
  } else {
    options = defaults;
  }
  const hasher = createHasher(options);
  hasher.dispatch(object);
  return hasher.toString();
}
const defaultPrototypesKeys = Object.freeze([
  "prototype",
  "__proto__",
  "constructor"
]);
function createHasher(options) {
  let buff = "";
  let context = /* @__PURE__ */ new Map();
  const write = (str) => {
    buff += str;
  };
  return {
    toString() {
      return buff;
    },
    getContext() {
      return context;
    },
    dispatch(value) {
      if (options.replacer) {
        value = options.replacer(value);
      }
      const type = value === null ? "null" : typeof value;
      return this[type](value);
    },
    object(object) {
      if (object && typeof object.toJSON === "function") {
        return this.object(object.toJSON());
      }
      const objString = Object.prototype.toString.call(object);
      let objType = "";
      const objectLength = objString.length;
      if (objectLength < 10) {
        objType = "unknown:[" + objString + "]";
      } else {
        objType = objString.slice(8, objectLength - 1);
      }
      objType = objType.toLowerCase();
      let objectNumber = null;
      if ((objectNumber = context.get(object)) === void 0) {
        context.set(object, context.size);
      } else {
        return this.dispatch("[CIRCULAR:" + objectNumber + "]");
      }
      if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) {
        write("buffer:");
        return write(object.toString("utf8"));
      }
      if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") {
        if (this[objType]) {
          this[objType](object);
        } else if (!options.ignoreUnknown) {
          this.unkown(object, objType);
        }
      } else {
        let keys = Object.keys(object);
        if (options.unorderedObjects) {
          keys = keys.sort();
        }
        let extraKeys = [];
        if (options.respectType !== false && !isNativeFunction(object)) {
          extraKeys = defaultPrototypesKeys;
        }
        if (options.excludeKeys) {
          keys = keys.filter((key) => {
            return !options.excludeKeys(key);
          });
          extraKeys = extraKeys.filter((key) => {
            return !options.excludeKeys(key);
          });
        }
        write("object:" + (keys.length + extraKeys.length) + ":");
        const dispatchForKey = (key) => {
          this.dispatch(key);
          write(":");
          if (!options.excludeValues) {
            this.dispatch(object[key]);
          }
          write(",");
        };
        for (const key of keys) {
          dispatchForKey(key);
        }
        for (const key of extraKeys) {
          dispatchForKey(key);
        }
      }
    },
    array(arr, unordered) {
      unordered = unordered === void 0 ? options.unorderedArrays !== false : unordered;
      write("array:" + arr.length + ":");
      if (!unordered || arr.length <= 1) {
        for (const entry of arr) {
          this.dispatch(entry);
        }
        return;
      }
      const contextAdditions = /* @__PURE__ */ new Map();
      const entries = arr.map((entry) => {
        const hasher = createHasher(options);
        hasher.dispatch(entry);
        for (const [key, value] of hasher.getContext()) {
          contextAdditions.set(key, value);
        }
        return hasher.toString();
      });
      context = contextAdditions;
      entries.sort();
      return this.array(entries, false);
    },
    date(date) {
      return write("date:" + date.toJSON());
    },
    symbol(sym) {
      return write("symbol:" + sym.toString());
    },
    unkown(value, type) {
      write(type);
      if (!value) {
        return;
      }
      write(":");
      if (value && typeof value.entries === "function") {
        return this.array(
          Array.from(value.entries()),
          true
          /* ordered */
        );
      }
    },
    error(err) {
      return write("error:" + err.toString());
    },
    boolean(bool) {
      return write("bool:" + bool);
    },
    string(string) {
      write("string:" + string.length + ":");
      write(string);
    },
    function(fn) {
      write("fn:");
      if (isNativeFunction(fn)) {
        this.dispatch("[native]");
      } else {
        this.dispatch(fn.toString());
      }
      if (options.respectFunctionNames !== false) {
        this.dispatch("function-name:" + String(fn.name));
      }
      if (options.respectFunctionProperties) {
        this.object(fn);
      }
    },
    number(number) {
      return write("number:" + number);
    },
    xml(xml) {
      return write("xml:" + xml.toString());
    },
    null() {
      return write("Null");
    },
    undefined() {
      return write("Undefined");
    },
    regexp(regex) {
      return write("regex:" + regex.toString());
    },
    uint8array(arr) {
      write("uint8array:");
      return this.dispatch(Array.prototype.slice.call(arr));
    },
    uint8clampedarray(arr) {
      write("uint8clampedarray:");
      return this.dispatch(Array.prototype.slice.call(arr));
    },
    int8array(arr) {
      write("int8array:");
      return this.dispatch(Array.prototype.slice.call(arr));
    },
    uint16array(arr) {
      write("uint16array:");
      return this.dispatch(Array.prototype.slice.call(arr));
    },
    int16array(arr) {
      write("int16array:");
      return this.dispatch(Array.prototype.slice.call(arr));
    },
    uint32array(arr) {
      write("uint32array:");
      return this.dispatch(Array.prototype.slice.call(arr));
    },
    int32array(arr) {
      write("int32array:");
      return this.dispatch(Array.prototype.slice.call(arr));
    },
    float32array(arr) {
      write("float32array:");
      return this.dispatch(Array.prototype.slice.call(arr));
    },
    float64array(arr) {
      write("float64array:");
      return this.dispatch(Array.prototype.slice.call(arr));
    },
    arraybuffer(arr) {
      write("arraybuffer:");
      return this.dispatch(new Uint8Array(arr));
    },
    url(url) {
      return write("url:" + url.toString());
    },
    map(map) {
      write("map:");
      const arr = [...map];
      return this.array(arr, options.unorderedSets !== false);
    },
    set(set) {
      write("set:");
      const arr = [...set];
      return this.array(arr, options.unorderedSets !== false);
    },
    file(file) {
      write("file:");
      return this.dispatch([file.name, file.size, file.type, file.lastModfied]);
    },
    blob() {
      if (options.ignoreUnknown) {
        return write("[blob]");
      }
      throw new Error(
        'Hashing Blob objects is currently not supported\nUse "options.replacer" or "options.ignoreUnknown"\n'
      );
    },
    domwindow() {
      return write("domwindow");
    },
    bigint(number) {
      return write("bigint:" + number.toString());
    },
    /* Node.js standard native objects */
    process() {
      return write("process");
    },
    timer() {
      return write("timer");
    },
    pipe() {
      return write("pipe");
    },
    tcp() {
      return write("tcp");
    },
    udp() {
      return write("udp");
    },
    tty() {
      return write("tty");
    },
    statwatcher() {
      return write("statwatcher");
    },
    securecontext() {
      return write("securecontext");
    },
    connection() {
      return write("connection");
    },
    zlib() {
      return write("zlib");
    },
    context() {
      return write("context");
    },
    nodescript() {
      return write("nodescript");
    },
    httpparser() {
      return write("httpparser");
    },
    dataview() {
      return write("dataview");
    },
    signal() {
      return write("signal");
    },
    fsevent() {
      return write("fsevent");
    },
    tlswrap() {
      return write("tlswrap");
    }
  };
}
const nativeFunc = "[native code] }";
const nativeFuncLength = nativeFunc.length;
function isNativeFunction(f) {
  if (typeof f !== "function") {
    return false;
  }
  return Function.prototype.toString.call(f).slice(-nativeFuncLength) === nativeFunc;
}

class WordArray {
  words;
  sigBytes;
  constructor(words, sigBytes) {
    words = this.words = words || [];
    this.sigBytes = sigBytes === void 0 ? words.length * 4 : sigBytes;
  }
  toString(encoder) {
    return (encoder || Hex).stringify(this);
  }
  concat(wordArray) {
    this.clamp();
    if (this.sigBytes % 4) {
      for (let i = 0; i < wordArray.sigBytes; i++) {
        const thatByte = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
        this.words[this.sigBytes + i >>> 2] |= thatByte << 24 - (this.sigBytes + i) % 4 * 8;
      }
    } else {
      for (let j = 0; j < wordArray.sigBytes; j += 4) {
        this.words[this.sigBytes + j >>> 2] = wordArray.words[j >>> 2];
      }
    }
    this.sigBytes += wordArray.sigBytes;
    return this;
  }
  clamp() {
    this.words[this.sigBytes >>> 2] &= 4294967295 << 32 - this.sigBytes % 4 * 8;
    this.words.length = Math.ceil(this.sigBytes / 4);
  }
  clone() {
    return new WordArray([...this.words]);
  }
}
const Hex = {
  stringify(wordArray) {
    const hexChars = [];
    for (let i = 0; i < wordArray.sigBytes; i++) {
      const bite = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
      hexChars.push((bite >>> 4).toString(16), (bite & 15).toString(16));
    }
    return hexChars.join("");
  }
};
const Base64 = {
  stringify(wordArray) {
    const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    const base64Chars = [];
    for (let i = 0; i < wordArray.sigBytes; i += 3) {
      const byte1 = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
      const byte2 = wordArray.words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 255;
      const byte3 = wordArray.words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 255;
      const triplet = byte1 << 16 | byte2 << 8 | byte3;
      for (let j = 0; j < 4 && i * 8 + j * 6 < wordArray.sigBytes * 8; j++) {
        base64Chars.push(keyStr.charAt(triplet >>> 6 * (3 - j) & 63));
      }
    }
    return base64Chars.join("");
  }
};
const Latin1 = {
  parse(latin1Str) {
    const latin1StrLength = latin1Str.length;
    const words = [];
    for (let i = 0; i < latin1StrLength; i++) {
      words[i >>> 2] |= (latin1Str.charCodeAt(i) & 255) << 24 - i % 4 * 8;
    }
    return new WordArray(words, latin1StrLength);
  }
};
const Utf8 = {
  parse(utf8Str) {
    return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
  }
};
class BufferedBlockAlgorithm {
  _data = new WordArray();
  _nDataBytes = 0;
  _minBufferSize = 0;
  blockSize = 512 / 32;
  reset() {
    this._data = new WordArray();
    this._nDataBytes = 0;
  }
  _append(data) {
    if (typeof data === "string") {
      data = Utf8.parse(data);
    }
    this._data.concat(data);
    this._nDataBytes += data.sigBytes;
  }
  _doProcessBlock(_dataWords, _offset) {
  }
  _process(doFlush) {
    let processedWords;
    let nBlocksReady = this._data.sigBytes / (this.blockSize * 4);
    if (doFlush) {
      nBlocksReady = Math.ceil(nBlocksReady);
    } else {
      nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
    }
    const nWordsReady = nBlocksReady * this.blockSize;
    const nBytesReady = Math.min(nWordsReady * 4, this._data.sigBytes);
    if (nWordsReady) {
      for (let offset = 0; offset < nWordsReady; offset += this.blockSize) {
        this._doProcessBlock(this._data.words, offset);
      }
      processedWords = this._data.words.splice(0, nWordsReady);
      this._data.sigBytes -= nBytesReady;
    }
    return new WordArray(processedWords, nBytesReady);
  }
}
class Hasher extends BufferedBlockAlgorithm {
  update(messageUpdate) {
    this._append(messageUpdate);
    this._process();
    return this;
  }
  finalize(messageUpdate) {
    if (messageUpdate) {
      this._append(messageUpdate);
    }
  }
}

const H = [
  1779033703,
  -1150833019,
  1013904242,
  -1521486534,
  1359893119,
  -1694144372,
  528734635,
  1541459225
];
const K = [
  1116352408,
  1899447441,
  -1245643825,
  -373957723,
  961987163,
  1508970993,
  -1841331548,
  -1424204075,
  -670586216,
  310598401,
  607225278,
  1426881987,
  1925078388,
  -2132889090,
  -1680079193,
  -1046744716,
  -459576895,
  -272742522,
  264347078,
  604807628,
  770255983,
  1249150122,
  1555081692,
  1996064986,
  -1740746414,
  -1473132947,
  -1341970488,
  -1084653625,
  -958395405,
  -710438585,
  113926993,
  338241895,
  666307205,
  773529912,
  1294757372,
  1396182291,
  1695183700,
  1986661051,
  -2117940946,
  -1838011259,
  -1564481375,
  -1474664885,
  -1035236496,
  -949202525,
  -778901479,
  -694614492,
  -200395387,
  275423344,
  430227734,
  506948616,
  659060556,
  883997877,
  958139571,
  1322822218,
  1537002063,
  1747873779,
  1955562222,
  2024104815,
  -2067236844,
  -1933114872,
  -1866530822,
  -1538233109,
  -1090935817,
  -965641998
];
const W = [];
class SHA256 extends Hasher {
  _hash = new WordArray([...H]);
  /**
   * Resets the internal state of the hash object to initial values.
   */
  reset() {
    super.reset();
    this._hash = new WordArray([...H]);
  }
  _doProcessBlock(M, offset) {
    const H2 = this._hash.words;
    let a = H2[0];
    let b = H2[1];
    let c = H2[2];
    let d = H2[3];
    let e = H2[4];
    let f = H2[5];
    let g = H2[6];
    let h = H2[7];
    for (let i = 0; i < 64; i++) {
      if (i < 16) {
        W[i] = M[offset + i] | 0;
      } else {
        const gamma0x = W[i - 15];
        const gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
        const gamma1x = W[i - 2];
        const gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
        W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
      }
      const ch = e & f ^ ~e & g;
      const maj = a & b ^ a & c ^ b & c;
      const sigma0 = (a << 30 | a >>> 2) ^ (a << 19 | a >>> 13) ^ (a << 10 | a >>> 22);
      const sigma1 = (e << 26 | e >>> 6) ^ (e << 21 | e >>> 11) ^ (e << 7 | e >>> 25);
      const t1 = h + sigma1 + ch + K[i] + W[i];
      const t2 = sigma0 + maj;
      h = g;
      g = f;
      f = e;
      e = d + t1 | 0;
      d = c;
      c = b;
      b = a;
      a = t1 + t2 | 0;
    }
    H2[0] = H2[0] + a | 0;
    H2[1] = H2[1] + b | 0;
    H2[2] = H2[2] + c | 0;
    H2[3] = H2[3] + d | 0;
    H2[4] = H2[4] + e | 0;
    H2[5] = H2[5] + f | 0;
    H2[6] = H2[6] + g | 0;
    H2[7] = H2[7] + h | 0;
  }
  /**
   * Finishes the hash calculation and returns the hash as a WordArray.
   *
   * @param {string} messageUpdate - Additional message content to include in the hash.
   * @returns {WordArray} The finalised hash as a WordArray.
   */
  finalize(messageUpdate) {
    super.finalize(messageUpdate);
    const nBitsTotal = this._nDataBytes * 8;
    const nBitsLeft = this._data.sigBytes * 8;
    this._data.words[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
    this._data.words[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(
      nBitsTotal / 4294967296
    );
    this._data.words[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
    this._data.sigBytes = this._data.words.length * 4;
    this._process();
    return this._hash;
  }
}
function sha256base64(message) {
  return new SHA256().finalize(message).toString(Base64);
}

function hash(object, options = {}) {
  const hashed = typeof object === "string" ? object : objectHash(object, options);
  return sha256base64(hashed).slice(0, 10);
}

class CloudCache {
  memoryCache;
  cacheDir;
  enabled;
  constructor(config) {
    this.memoryCache = /* @__PURE__ */ new Map();
    this.enabled = config.enableCache !== false;
    this.cacheDir = config.cacheDir || path__default.join(process.cwd(), ".ccjk-cache");
    if (this.enabled) {
      this.ensureCacheDir();
      this.loadCacheFromDisk();
    }
  }
  /**
   * Ensure cache directory exists
   */
  ensureCacheDir() {
    try {
      if (!fs__default.existsSync(this.cacheDir)) {
        fs__default.mkdirSync(this.cacheDir, { recursive: true });
        consola.debug("Created cache directory:", this.cacheDir);
      }
    } catch (error) {
      consola.warn("Failed to create cache directory, disabling cache:", error);
      this.enabled = false;
    }
  }
  /**
   * Load cache from disk
   */
  loadCacheFromDisk() {
    try {
      const cacheFile = path__default.join(this.cacheDir, "cache.json");
      if (fs__default.existsSync(cacheFile)) {
        const data = fs__default.readFileSync(cacheFile, "utf-8");
        const entries = JSON.parse(data);
        const now = Date.now();
        for (const [key, entry] of Object.entries(entries)) {
          if (entry.expiresAt > now) {
            this.memoryCache.set(key, entry);
          }
        }
        consola.debug(`Loaded ${this.memoryCache.size} cache entries from disk`);
      }
    } catch (error) {
      consola.warn("Failed to load cache from disk:", error);
    }
  }
  /**
   * Save cache to disk
   */
  saveCacheToDisk() {
    try {
      const cacheFile = path__default.join(this.cacheDir, "cache.json");
      const entries = Object.fromEntries(this.memoryCache);
      fs__default.writeFileSync(cacheFile, JSON.stringify(entries, null, 2));
    } catch (error) {
      consola.warn("Failed to save cache to disk:", error);
    }
  }
  /**
   * Generate cache key from parameters
   */
  generateKey(prefix, params) {
    const hashValue = hash(params);
    return `${prefix}:${hashValue}`;
  }
  /**
   * Get cached value
   *
   * @param key - Cache key
   * @returns Cached value or undefined if not found/expired
   */
  get(key) {
    if (!this.enabled) {
      return void 0;
    }
    const entry = this.memoryCache.get(key);
    if (!entry) {
      return void 0;
    }
    if (Date.now() > entry.expiresAt) {
      this.memoryCache.delete(key);
      this.saveCacheToDisk();
      return void 0;
    }
    consola.debug(`Cache hit: ${key}`);
    return entry.data;
  }
  /**
   * Set cached value with TTL
   *
   * @param key - Cache key
   * @param value - Value to cache
   * @param ttlSeconds - Time to live in seconds
   */
  set(key, value, ttlSeconds) {
    if (!this.enabled) {
      return;
    }
    const entry = {
      data: value,
      expiresAt: Date.now() + ttlSeconds * 1e3,
      key
    };
    this.memoryCache.set(key, entry);
    this.saveCacheToDisk();
    consola.debug(`Cache set: ${key} (TTL: ${ttlSeconds}s)`);
  }
  /**
   * Delete cache entry
   *
   * @param key - Cache key
   */
  delete(key) {
    this.memoryCache.delete(key);
    this.saveCacheToDisk();
    consola.debug(`Cache deleted: ${key}`);
  }
  /**
   * Clear all cache entries
   */
  clear() {
    this.memoryCache.clear();
    this.saveCacheToDisk();
    consola.debug("Cache cleared");
  }
  /**
   * Clean expired entries
   */
  cleanExpired() {
    const now = Date.now();
    let cleaned = 0;
    for (const [key, entry] of this.memoryCache.entries()) {
      if (now > entry.expiresAt) {
        this.memoryCache.delete(key);
        cleaned++;
      }
    }
    if (cleaned > 0) {
      this.saveCacheToDisk();
      consola.debug(`Cleaned ${cleaned} expired cache entries`);
    }
  }
  /**
   * Get cache statistics
   */
  getStats() {
    return {
      size: this.memoryCache.size,
      keys: Array.from(this.memoryCache.keys())
    };
  }
}
class CachedCloudClient {
  client;
  cache;
  constructor(client, cache) {
    this.client = client;
    this.cache = cache;
  }
  /**
   * Analyze project with caching (7-day TTL)
   */
  async analyzeProject(request) {
    const cacheKey = this.cache.generateKey("analyze", request);
    const cached = this.cache.get(cacheKey);
    if (cached) {
      return cached;
    }
    const result = await this.client.analyzeProject(request);
    this.cache.set(cacheKey, result, 7 * 24 * 60 * 60);
    return result;
  }
  /**
   * Get template with caching (30-day TTL)
   */
  async getTemplate(id, language) {
    const cacheKey = this.cache.generateKey("template", { id, language });
    const cached = this.cache.get(cacheKey);
    if (cached) {
      return cached;
    }
    const result = await this.client.getTemplate(id, language);
    this.cache.set(cacheKey, result, 30 * 24 * 60 * 60);
    return result;
  }
  /**
   * Get batch templates with caching (30-day TTL)
   */
  async getBatchTemplates(request) {
    const cacheKey = this.cache.generateKey("batch", request);
    const cached = this.cache.get(cacheKey);
    if (cached) {
      return cached;
    }
    const result = await this.client.getBatchTemplates(request);
    this.cache.set(cacheKey, result, 30 * 24 * 60 * 60);
    return result;
  }
  /**
   * Report usage (no caching)
   */
  async reportUsage(report) {
    return this.client.reportUsage(report);
  }
  /**
   * Health check with caching (5-minute TTL)
   */
  async healthCheck() {
    const cacheKey = "health:check";
    const cached = this.cache.get(cacheKey);
    if (cached) {
      return cached;
    }
    const result = await this.client.healthCheck();
    this.cache.set(cacheKey, result, 5 * 60);
    return result;
  }
  /**
   * Clear cache
   */
  clearCache() {
    this.cache.clear();
  }
  /**
   * Clean expired cache entries
   */
  cleanCache() {
    this.cache.cleanExpired();
  }
  /**
   * Get cache statistics
   */
  getCacheStats() {
    return this.cache.getStats();
  }
  /**
   * Get underlying client
   */
  getClient() {
    return this.client;
  }
}

class CloudClientError extends Error {
  /** Error type */
  type;
  /** HTTP status code if applicable */
  statusCode;
  /** Original error */
  originalError;
  constructor(type, message, statusCode, originalError) {
    super(message);
    this.name = "CloudClientError";
    this.type = type;
    this.statusCode = statusCode;
    this.originalError = originalError;
  }
  /**
   * Create error from HTTP response
   */
  static fromResponse(statusCode, message) {
    let type;
    if (statusCode === 401)
      type = "AUTH_ERROR";
    else if (statusCode === 429)
      type = "RATE_LIMIT_ERROR";
    else if (statusCode >= 500)
      type = "SERVER_ERROR";
    else if (statusCode >= 400)
      type = "API_ERROR";
    else type = "UNKNOWN_ERROR";
    return new CloudClientError(type, message, statusCode);
  }
  /**
   * Create network error
   */
  static network(error) {
    return new CloudClientError(
      "NETWORK_ERROR",
      error instanceof Error ? error.message : "Network connection failed",
      void 0,
      error
    );
  }
  /**
   * Create timeout error
   */
  static timeout(timeout) {
    return new CloudClientError(
      "TIMEOUT_ERROR",
      `Request timeout after ${timeout}ms`
    );
  }
  /**
   * Create validation error
   */
  static validation(message) {
    return new CloudClientError("VALIDATION_ERROR", message);
  }
}

const __dirname = dirname(fileURLToPath(import.meta.url));
let CCJK_VERSION = "9.0.0";
try {
  const packageJson = JSON.parse(readFileSync(join(__dirname, "../../package.json"), "utf-8"));
  CCJK_VERSION = packageJson.version;
} catch {
}
const API_PREFIX = "/api/v1";
const HEALTH_PATH = `${API_PREFIX}/health`;
const CLIENT_USAGE_STATE_DIR = join(homedir(), ".ccjk");
const CLIENT_USAGE_STATE_FILE = join(CLIENT_USAGE_STATE_DIR, "cloud-client-identity.json");
class CloudClient {
  fetch;
  config;
  identity;
  constructor(config) {
    this.config = {
      timeout: 1e4,
      enableRetry: true,
      maxRetries: 3,
      enableTelemetry: true,
      enableUsageAnalytics: true,
      autoHandshake: true,
      ...config
    };
    this.identity = this.resolveIdentity();
    this.fetch = ofetch.create({
      baseURL: this.config.baseURL,
      timeout: this.config.timeout,
      headers: this.getDefaultHeaders(),
      retry: this.config.enableRetry ? this.config.maxRetries : 0,
      retryDelay: (context) => this.calculateRetryDelay(context.options.retry || 0)
    });
  }
  getDefaultHeaders() {
    const headers = {
      "User-Agent": `CCJK/${this.identity.clientVersion}`,
      "X-CCJK-Version": this.identity.clientVersion,
      "X-Anonymous-User-Id": this.identity.anonymousUserId
    };
    if (this.config.apiKey) {
      headers.Authorization = `Bearer ${this.config.apiKey}`;
    }
    if (this.identity.deviceToken) {
      headers["X-Device-Token"] = this.identity.deviceToken;
    }
    return headers;
  }
  resolveIdentity() {
    const storedIdentity = this.loadOrCreateStoredIdentity();
    const clientVersion = this.config.version || CCJK_VERSION;
    return {
      anonymousUserId: this.config.anonymousUserId || storedIdentity.anonymousUserId,
      deviceId: this.config.deviceId || storedIdentity.deviceId,
      clientVersion,
      platform: this.config.platform || process.platform,
      deviceToken: this.config.deviceToken
    };
  }
  loadOrCreateStoredIdentity() {
    try {
      if (existsSync(CLIENT_USAGE_STATE_FILE)) {
        const stored = JSON.parse(readFileSync(CLIENT_USAGE_STATE_FILE, "utf-8"));
        if (stored.anonymousUserId && stored.deviceId) {
          return {
            anonymousUserId: stored.anonymousUserId,
            deviceId: stored.deviceId
          };
        }
      }
    } catch (error) {
      consola.debug("Failed to read stored cloud client identity:", error);
    }
    const generated = {
      anonymousUserId: process.env.CCJK_ANONYMOUS_USER_ID || randomUUID(),
      deviceId: process.env.CCJK_DEVICE_ID || randomUUID()
    };
    try {
      mkdirSync(CLIENT_USAGE_STATE_DIR, { recursive: true });
      writeFileSync(CLIENT_USAGE_STATE_FILE, JSON.stringify(generated, null, 2));
    } catch (error) {
      consola.debug("Failed to persist cloud client identity:", error);
    }
    return generated;
  }
  buildAnalyticsPayload(payload) {
    return {
      deviceId: payload?.deviceId || this.identity.deviceId,
      platform: payload?.platform || this.identity.platform,
      clientVersion: payload?.clientVersion || this.identity.clientVersion,
      ...payload
    };
  }
  canSendUsageAnalytics() {
    return this.config.enableUsageAnalytics !== false;
  }
  getIdentity() {
    return { ...this.identity };
  }
  /**
   * Calculate retry delay with exponential backoff
   */
  calculateRetryDelay(attempt) {
    const delays = [100, 200, 400, 800];
    return delays[Math.min(attempt, delays.length - 1)];
  }
  /**
   * Parse server response — handles all 5 response formats from Miaoda API:
   * 1. { success: true, data: {} }  — auth/user/config/admin modules
   * 2. { success: false, error: { message } }  — error from above modules
   * 3. { data: {} }  — usage/license/skill modules
   * 4. bare object  — subscription/llm/storage modules
   * 5. { error: "..." }  — bare error
   */
  parseResponse(raw) {
    if (raw === null || raw === void 0)
      return raw;
    const r = raw;
    if (r.success === false) {
      const msg = r.error?.message || r.message || r.error || "Unknown error";
      throw new CloudClientError("API_ERROR", String(msg));
    }
    if (r.success === true && "data" in r)
      return r.data;
    if (!("success" in r) && "data" in r)
      return r.data;
    if (typeof r.error === "string" && !("data" in r))
      throw new CloudClientError("API_ERROR", r.error);
    return raw;
  }
  /**
   * Handle fetch errors and convert to CloudClientError
   */
  handleError(error, context) {
    if (error instanceof CloudClientError) {
      throw error;
    }
    if (error instanceof Error) {
      const errorMessage = error.message || "";
      if (errorMessage.includes("timeout") || errorMessage.includes("timed out")) {
        throw CloudClientError.timeout(this.config.timeout || 1e4);
      }
      if (errorMessage.includes("ECONNREFUSED") || errorMessage.includes("ENOTFOUND")) {
        throw CloudClientError.network(error);
      }
      const statusMatch = errorMessage.match(/(\d{3})\s+/);
      const statusCode = statusMatch ? Number.parseInt(statusMatch[1]) : void 0;
      let responseDetails = errorMessage;
      try {
        if (errorMessage.includes(":")) {
          const parts = errorMessage.split(":");
          if (parts.length > 1) {
            responseDetails = parts.slice(1).join(":").trim();
          }
        }
      } catch {
      }
      consola.warn(`Cloud API error in ${context}:`, {
        statusCode,
        message: responseDetails,
        originalError: error
      });
      if (statusCode) {
        throw CloudClientError.fromResponse(statusCode, responseDetails);
      }
      throw new CloudClientError(
        "UNKNOWN_ERROR",
        `Unexpected error during ${context}: ${responseDetails}`,
        void 0,
        error
      );
    }
    consola.warn(`Cloud API error in ${context}:`, error);
    throw new CloudClientError(
      "UNKNOWN_ERROR",
      `Unexpected error during ${context}`,
      void 0,
      error
    );
  }
  /**
   * Analyze project and get recommendations
   *
   * POST /api/v1/analysis/projects
   *
   * @param request - Project analysis request
   * @returns Project analysis response with recommendations
   */
  async analyzeProject(request) {
    try {
      consola.debug("Analyzing project:", request.projectRoot);
      const response = await this.fetch(`${API_PREFIX}/specs`, {
        method: "POST",
        body: request
      });
      consola.debug(`Received ${response.recommendations.length} recommendations`);
      return response;
    } catch (error) {
      this.handleError(error, "project analysis");
    }
  }
  /**
   * Get a single template by ID
   *
   * GET /api/v1/templates/:id
   *
   * @param id - Template identifier
   * @param language - Language for translations (optional)
   * @returns Template response
   */
  async getTemplate(id, language) {
    try {
      consola.debug("Fetching template:", id);
      const response = await this.fetch(`${API_PREFIX}/templates/${encodeURIComponent(id)}`, {
        method: "GET",
        params: language ? { language } : void 0
      });
      consola.debug(`Template ${id} fetched successfully`);
      return response;
    } catch (error) {
      this.handleError(error, `template fetch: ${id}`);
    }
  }
  /**
   * Get multiple templates in batch
   *
   * POST /api/v1/templates/batch
   *
   * @param request - Batch template request
   * @returns Batch template response
   */
  async getBatchTemplates(request) {
    try {
      consola.debug("Fetching batch templates:", request.ids.length);
      const response = await this.fetch(`${API_PREFIX}/templates/batch`, {
        method: "POST",
        body: request
      });
      consola.debug(`Fetched ${Object.keys(response.templates).length} templates`);
      return response;
    } catch (error) {
      this.handleError(error, "batch template fetch");
    }
  }
  /**
   * Report usage metrics (non-blocking with short timeout)
   *
   * POST /api/v1/telemetry/installation
   *
   * @param report - Usage report payload
   * @returns Usage report response
   */
  async reportUsage(report) {
    if (!this.canSendUsageAnalytics()) {
      return {
        success: false,
        requestId: "",
        message: "Usage analytics disabled"
      };
    }
    try {
      consola.debug("Reporting usage:", report.metricType);
      const payload = {
        ...report,
        deviceId: report.deviceId || this.identity.deviceId,
        platform: report.platform || this.identity.platform,
        clientVersion: report.clientVersion || report.ccjkVersion || this.identity.clientVersion
      };
      const response = await this.fetch(`${API_PREFIX}/usage/current`, {
        method: "POST",
        body: payload,
        timeout: 5e3
        // 5s timeout - telemetry should be fast
      });
      consola.debug("Usage report accepted");
      return response;
    } catch (error) {
      consola.debug("Failed to report usage (non-blocking):", error);
      return {
        success: false,
        requestId: "",
        message: error instanceof Error ? error.message : "Unknown error"
      };
    }
  }
  /**
   * Check API health status
   *
   * GET /api/v1/health
   *
   * @returns Health check response
   */
  async healthCheck() {
    try {
      consola.debug("Checking API health");
      const response = await this.fetch(HEALTH_PATH, {
        method: "GET"
      });
      consola.debug(`API health: ${response.status}`);
      return response;
    } catch (error) {
      this.handleError(error, "health check");
    }
  }
  /**
   * Update client configuration
   *
   * @param config - Partial configuration to update
   */
  updateConfig(config) {
    this.config = { ...this.config, ...config };
    this.identity = this.resolveIdentity();
    if (config.baseURL || config.timeout || config.apiKey || config.version || config.deviceToken || config.anonymousUserId || config.deviceId || config.platform) {
      this.fetch = ofetch.create({
        baseURL: this.config.baseURL,
        timeout: this.config.timeout,
        headers: this.getDefaultHeaders(),
        retry: this.config.enableRetry ? this.config.maxRetries : 0,
        retryDelay: (context) => this.calculateRetryDelay(context.options.retry || 0)
      });
    }
  }
  /**
   * Get current configuration
   */
  getConfig() {
    return { ...this.config };
  }
  async registerDevice(payload) {
    if (!this.canSendUsageAnalytics()) {
      return {
        success: false,
        message: "Usage analytics disabled"
      };
    }
    try {
      return await this.fetch("/device/register", {
        method: "POST",
        body: this.buildAnalyticsPayload(payload),
        timeout: 5e3
      });
    } catch (error) {
      consola.debug("Failed to register device (non-blocking):", error);
      return {
        success: false,
        requestId: "",
        message: error instanceof Error ? error.message : "Unknown error"
      };
    }
  }
  async handshake(payload) {
    if (!this.canSendUsageAnalytics()) {
      return {
        success: false,
        message: "Usage analytics disabled"
      };
    }
    try {
      return await this.fetch(`${API_PREFIX}/handshake`, {
        method: "POST",
        body: this.buildAnalyticsPayload(payload),
        timeout: 5e3
      });
    } catch (error) {
      consola.debug("Failed to send handshake (non-blocking):", error);
      return {
        success: false,
        requestId: "",
        message: error instanceof Error ? error.message : "Unknown error"
      };
    }
  }
  async syncClientUsage(payload) {
    if (!this.canSendUsageAnalytics()) {
      return {
        success: false,
        message: "Usage analytics disabled"
      };
    }
    try {
      return await this.fetch(`${API_PREFIX}/sync`, {
        method: "POST",
        body: this.buildAnalyticsPayload(payload),
        timeout: 5e3
      });
    } catch (error) {
      consola.debug("Failed to sync client usage (non-blocking):", error);
      return {
        success: false,
        requestId: "",
        message: error instanceof Error ? error.message : "Unknown error"
      };
    }
  }
}
function createCloudClient(config) {
  return new CloudClient({
    baseURL: CLOUD_ENDPOINTS.MAIN.BASE_URL,
    timeout: 1e4,
    version: CCJK_VERSION,
    enableCache: true,
    enableRetry: true,
    maxRetries: 3,
    enableTelemetry: true,
    ...config
  });
}

const DEFAULT_RETRY_CONFIG = {
  maxAttempts: 3,
  initialDelay: 100,
  multiplier: 2,
  maxDelay: 800,
  retryableStatusCodes: [500, 502, 503, 504, 408, 429]
};
async function withRetry(fn, config = {}) {
  const retryConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
  let lastError;
  for (let attempt = 0; attempt < retryConfig.maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;
      if (!shouldRetry(error, retryConfig, attempt)) {
        throw error;
      }
      const delay = Math.min(
        retryConfig.initialDelay * retryConfig.multiplier ** attempt,
        retryConfig.maxDelay
      );
      consola.warn(
        `Request failed (attempt ${attempt + 1}/${retryConfig.maxAttempts}), retrying in ${delay}ms:`,
        error instanceof Error ? error.message : error
      );
      await sleep(delay);
    }
  }
  throw lastError;
}
function shouldRetry(error, config, attempt) {
  if (attempt >= config.maxAttempts - 1) {
    return false;
  }
  if (error instanceof CloudClientError) {
    if (error.type === "VALIDATION_ERROR" || error.type === "AUTH_ERROR") {
      return false;
    }
    if (error.type === "NETWORK_ERROR" || error.type === "TIMEOUT_ERROR") {
      return true;
    }
    if (error.statusCode && config.retryableStatusCodes.includes(error.statusCode)) {
      return true;
    }
  }
  if (error instanceof Error) {
    const message = error.message.toLowerCase();
    if (message.includes("network") || message.includes("connection") || message.includes("timeout") || message.includes("econnrefused") || message.includes("enotfound")) {
      return true;
    }
  }
  return false;
}
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
class RetryableCloudClient {
  client;
  retryConfig;
  constructor(client, retryConfig = {}) {
    this.client = client;
    this.retryConfig = retryConfig;
  }
  /**
   * Analyze project with retry
   */
  analyzeProject = async (request) => {
    return withRetry(
      () => this.client.analyzeProject(request),
      this.retryConfig
    );
  };
  /**
   * Get template with retry
   */
  getTemplate = async (id, language) => {
    return withRetry(
      () => this.client.getTemplate(id, language),
      this.retryConfig
    );
  };
  /**
   * Get batch templates with retry
   */
  getBatchTemplates = async (request) => {
    return withRetry(
      () => this.client.getBatchTemplates(request),
      this.retryConfig
    );
  };
  /**
   * Report usage (no retry)
   */
  reportUsage = async (report) => {
    return this.client.reportUsage(report);
  };
  /**
   * Health check (no retry)
   */
  healthCheck = async () => {
    return withRetry(
      () => this.client.healthCheck(),
      this.retryConfig
    );
  };
  /**
   * Get underlying client
   */
  getClient() {
    return this.client;
  }
}
const retryUtils = {
  /**
   * Retry a function with exponential backoff
   */
  withRetry,
  /**
   * Calculate retry delay
   */
  calculateDelay(attempt, initialDelay = 100, multiplier = 2, maxDelay = 800) {
    return Math.min(
      initialDelay * multiplier ** attempt,
      maxDelay
    );
  },
  /**
   * Check if error is retryable
   */
  isRetryable(error) {
    if (error instanceof CloudClientError) {
      return error.type === "NETWORK_ERROR" || error.type === "TIMEOUT_ERROR" || error.statusCode !== void 0 && [500, 502, 503, 504, 408, 429].includes(error.statusCode);
    }
    if (error instanceof Error) {
      const message = error.message.toLowerCase();
      return message.includes("network") || message.includes("connection") || message.includes("timeout") || message.includes("econnrefused") || message.includes("enotfound");
    }
    return false;
  }
};

const DEFAULT_TELEMETRY_CONFIG = {
  enabled: true,
  batchSize: 10,
  flushInterval: 3e4
  // 30 seconds
};
class TelemetryReporter {
  client;
  config;
  events = [];
  flushTimer;
  userId;
  constructor(client, config = {}) {
    this.client = client;
    this.config = { ...DEFAULT_TELEMETRY_CONFIG, ...config };
    this.userId = this.config.userId || this.client.getIdentity().anonymousUserId || this.generateUserId();
    if (this.config.enabled) {
      this.startFlushTimer();
    }
  }
  /**
   * Generate or load anonymous user ID
   */
  generateUserId() {
    const envUserId = process.env.CCJK_TELEMETRY_USER_ID;
    if (envUserId) {
      return envUserId;
    }
    return randomUUID();
  }
  /**
   * Start periodic flush timer
   */
  startFlushTimer() {
    this.flushTimer = setInterval(() => {
      if (this.events.length > 0) {
        this.flush().catch((error) => {
          consola.debug("Failed to flush telemetry events:", error);
        });
      }
    }, this.config.flushInterval);
    this.flushTimer.unref();
  }
  /**
   * Stop flush timer
   */
  stopFlushTimer() {
    if (this.flushTimer) {
      clearInterval(this.flushTimer);
      this.flushTimer = void 0;
    }
  }
  /**
   * Check if telemetry is enabled
   */
  isEnabled() {
    if (process.env.CCJK_TELEMETRY === "false") {
      return false;
    }
    return this.config.enabled;
  }
  /**
   * Track an event (non-blocking)
   *
   * @param type - Event type
   * @param data - Additional event data
   */
  track(type, data) {
    if (!this.isEnabled()) {
      return;
    }
    const event = {
      type,
      data,
      // Type assertion needed for flexible telemetry data
      timestamp: (/* @__PURE__ */ new Date()).toISOString()
    };
    this.events.push(event);
    consola.debug(`Telemetry event tracked: ${type}`, data);
    if (this.events.length >= this.config.batchSize) {
      this.flush().catch((error) => {
        consola.debug("Telemetry flush failed (non-blocking):", error);
      });
    }
  }
  /**
   * Track template download
   */
  trackTemplateDownload(templateId, templateType) {
    this.track("template_download", {
      templateId,
      templateType,
      timestamp: Date.now()
    });
  }
  /**
   * Track recommendation shown
   */
  trackRecommendationShown(recommendationId, category) {
    this.track("recommendation_shown", {
      recommendationId,
      category,
      timestamp: Date.now()
    });
  }
  /**
   * Track recommendation accepted
   */
  trackRecommendationAccepted(recommendationId, category) {
    this.track("recommendation_accepted", {
      recommendationId,
      category,
      timestamp: Date.now()
    });
  }
  /**
   * Track analysis completed
   */
  trackAnalysisCompleted(projectType, frameworks) {
    this.track("analysis_completed", {
      projectType,
      frameworks,
      recommendationCount: frameworks?.length || 0,
      timestamp: Date.now()
    });
  }
  /**
   * Track error occurred
   */
  trackError(errorType, errorMessage, context) {
    this.track("error_occurred", {
      errorType,
      errorMessage,
      context,
      timestamp: Date.now()
    });
  }
  /**
   * Flush pending events to server (non-blocking)
   * Errors are caught and logged silently
   */
  async flush() {
    if (!this.isEnabled() || this.events.length === 0) {
      return;
    }
    const eventsToSend = [...this.events];
    this.events = [];
    try {
      consola.debug(`Flushing ${eventsToSend.length} telemetry events`);
      const batchSize = 100;
      for (let i = 0; i < eventsToSend.length; i += batchSize) {
        const batch = eventsToSend.slice(i, i + batchSize);
        await this.sendBatch(batch);
      }
      consola.debug("Telemetry events flushed successfully");
    } catch (error) {
      consola.debug("Telemetry flush failed silently:", error);
    }
  }
  /**
   * Send a batch of events (non-blocking with retry budget)
   */
  async sendBatch(events) {
    const report = {
      reportId: randomUUID(),
      metricType: "analysis_completed",
      // Batch metric type
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      ccjkVersion: process.env.npm_package_version || "8.0.0",
      nodeVersion: process.version,
      platform: process.platform,
      data: {
        events,
        batchSize: events.length,
        userId: this.userId
      }
    };
    await this.sendWithRetry(report, 3, 5e3);
  }
  /**
   * Send telemetry with retry budget and short timeout
   * Non-blocking: failures are logged but not thrown
   */
  async sendWithRetry(report, maxAttempts, timeout) {
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
      try {
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error("Telemetry timeout")), timeout);
        });
        await Promise.race([
          this.client.reportUsage(report),
          timeoutPromise
        ]);
        consola.debug(`Telemetry sent successfully (attempt ${attempt}/${maxAttempts})`);
        return;
      } catch (error) {
        consola.debug(
          `Telemetry attempt ${attempt}/${maxAttempts} failed:`,
          error instanceof Error ? error.message : error
        );
        if (attempt === maxAttempts) {
          consola.debug("Telemetry failed after all retry attempts - giving up silently");
          return;
        }
        const delay = 100 * 2 ** (attempt - 1);
        await new Promise((resolve) => setTimeout(resolve, delay));
      }
    }
  }
  /**
   * Stop telemetry and flush remaining events
   */
  async stop() {
    this.stopFlushTimer();
    if (this.events.length > 0) {
      await this.flush();
    }
  }
  /**
   * Get current queue size
   */
  getQueueSize() {
    return this.events.length;
  }
  /**
   * Get telemetry status
   */
  getStatus() {
    return {
      enabled: this.isEnabled(),
      queueSize: this.getQueueSize(),
      userId: this.userId
    };
  }
  /**
   * Report usage directly (non-blocking)
   * Fire-and-forget with retry budget and short timeout
   *
   * @param report - Usage report to send
   */
  reportUsage(report) {
    if (!this.isEnabled()) {
      return;
    }
    this.sendWithRetry(report, 3, 5e3).catch((error) => {
      consola.debug("Direct usage report failed (non-blocking):", error);
    });
  }
}
let globalTelemetry;
function initializeTelemetry(client, config) {
  if (globalTelemetry) {
    globalTelemetry.stop().catch(() => {
    });
  }
  globalTelemetry = new TelemetryReporter(client, config);
  if (client.getConfig().autoHandshake !== false && client.getConfig().enableUsageAnalytics !== false) {
    client.handshake().catch((error) => {
      consola.debug("Failed to send startup handshake (non-blocking):", error);
    });
  }
  return globalTelemetry;
}
function getTelemetry() {
  return globalTelemetry;
}
async function stopTelemetry() {
  if (globalTelemetry) {
    await globalTelemetry.stop();
    globalTelemetry = void 0;
  }
}
function trackEvent(type, data) {
  if (globalTelemetry) {
    globalTelemetry.track(type, data);
  }
}
const telemetryUtils = {
  /**
   * Check if telemetry is enabled
   */
  isEnabled() {
    if (globalTelemetry) {
      return globalTelemetry.isEnabled();
    }
    return process.env.CCJK_TELEMETRY !== "false";
  },
  /**
   * Track with automatic error handling
   */
  trackSafe(type, data) {
    try {
      trackEvent(type, data);
    } catch (error) {
      consola.debug("Failed to track telemetry event:", error);
    }
  },
  /**
   * Get telemetry status
   */
  getStatus() {
    if (globalTelemetry) {
      return globalTelemetry.getStatus();
    }
    return { enabled: false, queueSize: 0, userId: "" };
  }
};

class FallbackCloudClient {
  client;
  fallbackEnabled;
  constructor(client, fallbackEnabled = true) {
    this.client = client;
    this.fallbackEnabled = fallbackEnabled;
  }
  /**
   * Analyze project with fallback
   */
  async analyzeProject(request) {
    try {
      return await this.client.analyzeProject(request);
    } catch (error) {
      if (this.fallbackEnabled) {
        consola.warn("Cloud API unavailable, using local recommendations");
        return this.getLocalRecommendations(request);
      }
      throw error;
    }
  }
  /**
   * Get template with fallback
   */
  async getTemplate(id, language) {
    try {
      return await this.client.getTemplate(id, language);
    } catch (error) {
      if (this.fallbackEnabled) {
        consola.warn("Cloud API unavailable, using local template");
        return this.getLocalTemplate(id, language);
      }
      throw error;
    }
  }
  /**
   * Get batch templates with fallback
   */
  async getBatchTemplates(request) {
    try {
      return await this.client.getBatchTemplates(request);
    } catch (error) {
      if (this.fallbackEnabled) {
        consola.warn("Cloud API unavailable, using local templates");
        return this.getLocalBatchTemplates(request);
      }
      throw error;
    }
  }
  /**
   * Report usage (no fallback)
   */
  async reportUsage(report) {
    return this.client.reportUsage(report);
  }
  async registerDevice(payload) {
    return this.client.registerDevice(payload);
  }
  async handshake(payload) {
    return this.client.handshake(payload);
  }
  async syncClientUsage(payload) {
    return this.client.syncClientUsage(payload);
  }
  /**
   * Health check (no fallback)
   */
  async healthCheck() {
    return this.client.healthCheck();
  }
  /**
   * Get local fallback recommendations
   */
  getLocalRecommendations(request) {
    const recommendations = [];
    if (request.devDependencies?.typescript || request.devDependencies?.tslib) {
      recommendations.push({
        id: "typescript-workflow",
        name: { "en": "TypeScript Workflow", "zh-CN": "TypeScript \u5DE5\u4F5C\u6D41" },
        description: { "en": "Enhanced TypeScript support", "zh-CN": "\u589E\u5F3A\u7684 TypeScript \u652F\u6301" },
        category: "skill",
        relevanceScore: 0.9,
        installCommand: "ccjk config switch typescript",
        tags: ["typescript", "type-checking"]
      });
    }
    if (request.dependencies?.react || request.dependencies?.["react-dom"]) {
      recommendations.push({
        id: "react-workflow",
        name: { "en": "React Workflow", "zh-CN": "React \u5DE5\u4F5C\u6D41" },
        description: { "en": "React development tools", "zh-CN": "React \u5F00\u53D1\u5DE5\u5177" },
        category: "skill",
        relevanceScore: 0.95,
        installCommand: "ccjk config switch react",
        tags: ["react", "jsx", "frontend"]
      });
    }
    if (request.dependencies?.express || request.dependencies?.fastify) {
      recommendations.push({
        id: "nodejs-workflow",
        name: { "en": "Node.js Workflow", "zh-CN": "Node.js \u5DE5\u4F5C\u6D41" },
        description: { "en": "Node.js development tools", "zh-CN": "Node.js \u5F00\u53D1\u5DE5\u5177" },
        category: "skill",
        relevanceScore: 0.9,
        installCommand: "ccjk config switch nodejs",
        tags: ["nodejs", "backend", "server"]
      });
    }
    if (request.gitRemote) {
      recommendations.push({
        id: "git-workflow",
        name: { "en": "Git Workflow", "zh-CN": "Git \u5DE5\u4F5C\u6D41" },
        description: { "en": "Git best practices", "zh-CN": "Git \u6700\u4F73\u5B9E\u8DF5" },
        category: "skill",
        relevanceScore: 0.8,
        installCommand: "ccjk config switch git",
        tags: ["git", "vcs"]
      });
    }
    return {
      requestId: "local-fallback",
      recommendations,
      projectType: this.detectProjectType(request),
      frameworks: this.detectFrameworks(request)
    };
  }
  /**
   * Get local fallback template
   */
  getLocalTemplate(id, _language) {
    const templates = {
      "basic-workflow": {
        id: "basic-workflow",
        type: "workflow",
        name: { "en": "Basic Workflow", "zh-CN": "\u57FA\u7840\u5DE5\u4F5C\u6D41" },
        description: { "en": "Basic development workflow", "zh-CN": "\u57FA\u7840\u5F00\u53D1\u5DE5\u4F5C\u6D41" },
        content: JSON.stringify({
          name: "basic",
          steps: ["init", "test", "build", "deploy"]
        }, null, 2),
        version: "1.0.0",
        createdAt: (/* @__PURE__ */ new Date()).toISOString(),
        updatedAt: (/* @__PURE__ */ new Date()).toISOString()
      }
    };
    return templates[id] || {
      id,
      type: "workflow",
      name: { "en": "Unknown Template", "zh-CN": "\u672A\u77E5\u6A21\u677F" },
      description: { "en": "Template not found", "zh-CN": "\u6A21\u677F\u672A\u627E\u5230" },
      content: "{}",
      version: "1.0.0",
      createdAt: (/* @__PURE__ */ new Date()).toISOString(),
      updatedAt: (/* @__PURE__ */ new Date()).toISOString()
    };
  }
  /**
   * Get local fallback batch templates
   */
  getLocalBatchTemplates(request) {
    const templates = {};
    const notFound = [];
    for (const id of request.ids) {
      try {
        templates[id] = this.getLocalTemplate(id, request.language);
      } catch {
        notFound.push(id);
      }
    }
    return {
      requestId: "local-fallback",
      templates,
      notFound
    };
  }
  /**
   * Detect project type
   */
  detectProjectType(request) {
    if (request.dependencies?.react)
      return "react";
    if (request.dependencies?.vue)
      return "vue";
    if (request.dependencies?.express)
      return "nodejs";
    if (request.devDependencies?.typescript)
      return "typescript";
    return "generic";
  }
  /**
   * Detect frameworks
   */
  detectFrameworks(request) {
    const frameworks = [];
    const deps = { ...request.dependencies, ...request.devDependencies };
    if (deps.react)
      frameworks.push("react");
    if (deps.vue)
      frameworks.push("vue");
    if (deps.angular)
      frameworks.push("angular");
    if (deps.svelte)
      frameworks.push("svelte");
    if (deps.express)
      frameworks.push("express");
    if (deps.fastify)
      frameworks.push("fastify");
    if (deps.typescript)
      frameworks.push("typescript");
    if (deps.webpack)
      frameworks.push("webpack");
    if (deps.vite)
      frameworks.push("vite");
    return frameworks;
  }
}
function createCompleteCloudClient(config) {
  const baseClient = createCloudClient(config);
  const retryClient = new RetryableCloudClient(baseClient);
  const cache = new CloudCache(baseClient.getConfig());
  const cachedClient = new CachedCloudClient(retryClient.getClient(), cache);
  const fallbackClient = new FallbackCloudClient(cachedClient.getClient());
  initializeTelemetry(baseClient);
  return fallbackClient;
}

export { CachedCloudClient as C, FallbackCloudClient as F, RetryableCloudClient as R, TelemetryReporter as T, createCloudClient as a, CloudCache as b, createCompleteCloudClient as c, CloudClient as d, trackEvent as e, getTelemetry as g, initializeTelemetry as i, retryUtils as r, stopTelemetry as s, telemetryUtils as t, withRetry as w };
