import type { GraphemeSegmentationMode, GraphemeSegmentationResult } from './types';
import { canUseIntlSegmenter, segmentWithIntlSegmenter } from './strategies/intlSegmenter';
import { segmentWithFallback } from './strategies/fallback';

/**
 * 把字符串切分为 grapheme clusters（字符簇）。
 *
 * 契约（必须）：
 * - clusters.join('') === text（不允许丢字符/改顺序）
 * - text=='' 时 clusters==[]
 * - 任何异常都必须降级到 fallback（保证可用性）
 */
export function segmentGraphemes(text: string, mode: GraphemeSegmentationMode = 'PREFERRED'): GraphemeSegmentationResult {
  const input = String(text ?? '');
  if (input === '') {
    return { clusters: [], meta: { strategy: 'FALLBACK', hadFallback: mode === 'FALLBACK' } };
  }

  // 强制 fallback
  if (mode === 'FALLBACK') {
    const clusters = segmentWithFallback(input);
    return { clusters, meta: { strategy: 'FALLBACK', hadFallback: true } };
  }

  // 优先 Intl.Segmenter
  if (canUseIntlSegmenter()) {
    try {
      const clusters = segmentWithIntlSegmenter(input);
      // 防御：必须可逆
      if (clusters.length > 0 && clusters.join('') === input) {
        return { clusters, meta: { strategy: 'INTL_SEGMENTER', hadFallback: false } };
      }
      // 若结果异常（空/丢字符），走 fallback
    } catch {
      // ignore -> fallback
    }
  }

  const clusters = segmentWithFallback(input);
  return { clusters, meta: { strategy: 'FALLBACK', hadFallback: true } };
}

