/**
 * Capability check only. The OPFS implementation itself lives in the browser
 * platform layer so universal project code never owns browser persistence.
 */
export function supportsOpfsProjectStorage(): boolean {
  return (
    typeof navigator !== 'undefined' &&
    typeof navigator.storage?.getDirectory === 'function'
  );
}

export type BrowserStorageHealth = {
  supported: boolean;
  persisted?: boolean;
  usageBytes?: number;
  quotaBytes?: number;
  usageRatio?: number;
};

export async function getBrowserStorageHealth(): Promise<BrowserStorageHealth> {
  if (typeof navigator === 'undefined' || !navigator.storage) {
    return { supported: false };
  }

  const [persisted, estimate] = await Promise.all([
    typeof navigator.storage.persisted === 'function'
      ? navigator.storage.persisted().catch(() => undefined)
      : Promise.resolve(undefined),
    typeof navigator.storage.estimate === 'function'
      ? navigator.storage.estimate().catch(() => undefined)
      : Promise.resolve(undefined),
  ]);

  const usageBytes = estimate?.usage;
  const quotaBytes = estimate?.quota;
  return {
    supported: true,
    persisted,
    usageBytes,
    quotaBytes,
    usageRatio:
      typeof usageBytes === 'number' &&
      typeof quotaBytes === 'number' &&
      quotaBytes > 0
        ? usageBytes / quotaBytes
        : undefined,
  };
}

function storagePersistenceMayPrompt(): boolean {
  if (typeof navigator === 'undefined') return false;
  const userAgent = navigator.userAgent || '';
  // Firefox can display a prominent site-storage permission prompt for
  // navigator.storage.persist(). Learnitive never requests that permission
  // automatically; Firefox continues to use normal IndexedDB/OPFS quota and
  // users can keep ZIP/Git backups without seeing an alarming browser modal.
  return /Firefox\/|FxiOS\//u.test(userAgent);
}

export async function requestPersistentBrowserStorage(): Promise<boolean> {
  if (typeof navigator === 'undefined' || !navigator.storage) return false;
  const alreadyPersisted = typeof navigator.storage.persisted === 'function'
    ? await navigator.storage.persisted().catch(() => false)
    : false;
  if (alreadyPersisted || storagePersistenceMayPrompt()) return alreadyPersisted;
  if (typeof navigator.storage.persist !== 'function') return false;
  return navigator.storage.persist().catch(() => false);
}
