// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// drugs_repository.dart
// Gets drug names from assets/drugs/drugs.txt
//
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/// Repository for drug-related data
class DrugsRepository {
  /// Cached drug names to avoid reloading
  List<String>? _cachedDrugNames;

  /// The specific asset path to the drugs file
  static const String _drugsFilePath = 'assets/drugs/drugs.txt';

  /// Loads drug names from the text file
  Future<List<String>> loadDrugNames() async {
    // Return cached results if available
    if (_cachedDrugNames != null && _cachedDrugNames!.isNotEmpty) {
      print('Using ${_cachedDrugNames!.length} cached drug names');
      return _cachedDrugNames!;
    }

    try {
      print('Attempting to load drugs list from $_drugsFilePath');
      // Load from assets/drugs/drugs.txt
      final fileContent = await rootBundle.loadString(_drugsFilePath);

      if (fileContent.isEmpty) {
        print('Warning: Drug file was loaded but is empty');
        return [];
      }

      final drugNames = _parseDrugNames(fileContent);
      print('Successfully loaded ${drugNames.length} drug names');

      // Cache the results
      _cachedDrugNames = drugNames;
      return drugNames;
    } catch (e) {
      print('Error loading drug names from $_drugsFilePath: $e');
      return [];
    }
  }

  /// Parse the file content into a list of drug names
  List<String> _parseDrugNames(String fileContent) {
    final drugNames = fileContent
        .split('\n')
        .where((drug) => drug.trim().isNotEmpty)
        .map((drug) => drug.trim())
        .toList();

    return drugNames;
  }
}

/// Provider for the drugs repository
final drugsRepositoryProvider = Provider<DrugsRepository>((ref) {
  return DrugsRepository();
});

/// Provider for the list of drug names
final drugNamesProvider = FutureProvider<List<String>>((ref) async {
  final repository = ref.watch(drugsRepositoryProvider);
  return repository.loadDrugNames();
});
