declare const __DEV__: boolean;

let idSequence = 0;

export function isDevRuntime(): boolean {
  return typeof __DEV__ !== 'undefined' && __DEV__;
}

export function logDev(message: string, details: Record<string, unknown> = {}): void {
  if (isDevRuntime()) {
    console.log(message, details);
  }
}

export function warnDev(message: string, details: Record<string, unknown> = {}): void {
  if (isDevRuntime()) {
    console.warn(message, details);
  }
}

export function createTimestampId(prefix: string): string {
  idSequence = idSequence >= 999_999 ? 1 : idSequence + 1;
  return `${prefix}_${Date.now()}_${idSequence}`;
}

export function createSafeCredentialDebug(secret: string): Record<string, unknown> {
  return {
    credentialDetected: secret ? 'yes' : 'no',
    credentialLength: secret.length,
  };
}

export async function readResponseText(response: Response): Promise<string> {
  try {
    return await response.text();
  } catch {
    return '';
  }
}

export function truncateForLog(value: string, maxLength = 500): string {
  if (value.length <= maxLength) return value;
  return `${value.slice(0, maxLength)}...`;
}

export async function fetchWithTimeout(
  url: string,
  init: RequestInit,
  timeoutMs: number,
): Promise<Response> {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);

  try {
    return await fetch(url, {
      ...init,
      signal: controller.signal,
    });
  } finally {
    clearTimeout(timeoutId);
  }
}

export function isAbortError(error: unknown): boolean {
  if (error instanceof Error) {
    return error.name === 'AbortError' || /\babort(?:ed)?\b/i.test(error.message);
  }

  if (!error || typeof error !== 'object') return false;
  const record = error as { name?: unknown; message?: unknown };
  return record.name === 'AbortError'
    || (typeof record.message === 'string' && /\babort(?:ed)?\b/i.test(record.message));
}
