import 'package:flutter_test/flutter_test.dart';
import 'package:tane/domain/seed_saving.dart';

/// Pure lookup/merge logic for the seed-saving guidance: a per-species entry
/// overrides its family default, a bare genus is a fallback, and unknown crops
/// resolve to null.
void main() {
  final data = parseSeedSaving('''
  {
    "families": {
      "Fabaceae": { "lifeCycle": "annual", "pollination": "self", "processing": "dry", "difficulty": "easy" },
      "Solanaceae": { "pollination": "self", "isolationMinM": 3, "isolationMaxM": 15 }
    },
    "species": {
      "Vicia faba": { "pollination": "cross", "vector": "insect", "isolationMinM": 180, "note": {"es": "aísla", "en": "isolate"} },
      "Cucurbita": { "pollination": "cross", "vector": "insect" }
    }
  }
  ''');

  test('a species entry overrides its family default', () {
    final g = data.guideFor(scientificName: 'Vicia faba', family: 'Fabaceae');
    expect(g, isNotNull);
    // Family said self+easy+annual; the species override flips pollination.
    expect(g!.pollination, Pollination.cross);
    expect(g.vector, PollinationVector.insect);
    expect(g.isolationMinM, 180);
    // Fields the species didn't set fall through to the family.
    expect(g.lifeCycle, LifeCycle.annual);
    expect(g.difficulty, SavingDifficulty.easy);
    expect(g.processing, SeedProcessing.dry);
  });

  test('a bare genus key is a fallback when the species is unlisted', () {
    final g = data.guideFor(scientificName: 'Cucurbita maxima', family: null);
    expect(g?.pollination, Pollination.cross);
    expect(g?.vector, PollinationVector.insect);
  });

  test('family-only lookup returns the family default', () {
    final g = data.guideFor(family: 'Solanaceae');
    expect(g?.pollination, Pollination.self);
    expect(g?.isolationMaxM, 15);
  });

  test('lookup is case-insensitive', () {
    expect(data.guideFor(family: 'fabaceae'), isNotNull);
    expect(data.guideFor(scientificName: 'vicia faba'), isNotNull);
  });

  test('an unknown crop resolves to null', () {
    expect(data.guideFor(scientificName: 'Musa acuminata', family: 'Musaceae'),
        isNull);
  });

  test('noteFor falls back to English then any language', () {
    final g = data.guideFor(scientificName: 'Vicia faba')!;
    expect(g.noteFor('es'), 'aísla');
    expect(g.noteFor('fr'), 'isolate'); // no fr → en
  });

  test('mergedWith unions notes with the override winning', () {
    const base = SeedSavingGuide(note: {'es': 'a', 'en': 'b'});
    const over = SeedSavingGuide(note: {'es': 'c'});
    expect(base.mergedWith(over).note, {'es': 'c', 'en': 'b'});
  });
}
