import 'package:flutter_test/flutter_test.dart';
import 'package:tane/services/ocr/ocr_language.dart';

void main() {
  group('parseAvailableOcrLanguages', () {
    test('strips the .traineddata suffix', () {
      final available = parseAvailableOcrLanguages(
        '{"files": ["eng.traineddata", "spa.traineddata"]}',
      );
      expect(available, {'eng', 'spa'});
    });

    test('empty / missing files yields empty set', () {
      expect(parseAvailableOcrLanguages('{}'), isEmpty);
      expect(parseAvailableOcrLanguages('{"files": []}'), isEmpty);
    });
  });

  group('tesseractCodeForLocale', () {
    test('maps ISO 639-1 to Tesseract codes', () {
      expect(tesseractCodeForLocale('es'), 'spa');
      expect(tesseractCodeForLocale('en'), 'eng');
      expect(tesseractCodeForLocale('ar'), 'ara');
      expect(tesseractCodeForLocale('zh'), 'chi_sim');
    });

    test('accepts full locale tags and is case-insensitive', () {
      expect(tesseractCodeForLocale('es_ES'), 'spa');
      expect(tesseractCodeForLocale('zh-Hans-CN'), 'chi_sim');
      expect(tesseractCodeForLocale('DE'), 'deu');
    });

    test('unmapped locale returns null', () {
      expect(tesseractCodeForLocale('xx'), isNull);
    });
  });

  group('resolveOcrLanguages', () {
    const bundled = {'eng', 'spa'};

    test('preferred locale comes first, baseline appended', () {
      expect(
        resolveOcrLanguages(preferredLocales: ['es'], available: bundled),
        'spa+eng',
      );
    });

    test('English preferred is not duplicated by the baseline', () {
      expect(
        resolveOcrLanguages(preferredLocales: ['en'], available: bundled),
        'eng',
      );
    });

    test('order follows preference, de-duplicated', () {
      expect(
        resolveOcrLanguages(
          preferredLocales: ['es', 'en', 'es'],
          available: bundled,
        ),
        'spa+eng',
      );
    });

    test('unbundled locale falls back to the Latin baseline', () {
      // German pack is not bundled here — degrade to eng, never fail.
      expect(
        resolveOcrLanguages(preferredLocales: ['de'], available: bundled),
        'eng',
      );
    });

    test('a future RTL/CJK pack lights up automatically once bundled', () {
      expect(
        resolveOcrLanguages(
          preferredLocales: ['ar'],
          available: {'eng', 'spa', 'ara'},
        ),
        'ara+eng',
      );
    });

    test('no baseline available: falls back to every bundled pack, sorted', () {
      expect(
        resolveOcrLanguages(
          preferredLocales: ['fr'],
          available: {'spa', 'deu'},
        ),
        'deu+spa',
      );
    });

    test('empty available yields empty string', () {
      expect(
        resolveOcrLanguages(preferredLocales: ['es'], available: const {}),
        '',
      );
    });
  });
}
