import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/network/dio_client.dart';
import '../../../knowledge_base/data/datasources/kb_remote_datasource.dart';
import '../../data/datasources/generator_remote_datasource.dart';
import '../../data/repositories/generator_repository_impl.dart';
import 'generator_state.dart';

class GeneratorCubit extends Cubit<GeneratorState> {
  final GeneratorRepositoryImpl _repo;
  List<String> _kbs = [];

  GeneratorCubit()
      : _repo = GeneratorRepositoryImpl(
            GeneratorRemoteDatasource(DioClient.instance)),
        super(const GeneratorInitial());

  Future<void> loadKnowledgeBases() async {
    try {
      _kbs = await KBRemoteDatasource(DioClient.instance).getKnowledgeBases();
      if (state is GeneratorInitial) {
        emit(GeneratorInitial(knowledgeBases: _kbs));
      }
    } catch (_) {}
  }

  List<String> get knowledgeBases => _kbs;

  Future<void> generate({
    required String stockSymbol,
    required int zscoreWindow,
    required double zscoreTriggerMin,
    required double zscoreTriggerMax,
    String? knowledgeBaseId,
  }) async {
    emit(const GeneratorRunning());
    try {
      final result = await _repo.generate(
        stockSymbol: stockSymbol,
        zscoreWindow: zscoreWindow,
        zscoreTriggerMin: zscoreTriggerMin,
        zscoreTriggerMax: zscoreTriggerMax,
        knowledgeBaseId: knowledgeBaseId,
      );
      emit(GeneratorSuccess(result));
    } catch (e) {
      emit(GeneratorError(e.toString()));
    }
  }

  void reset() {
    emit(GeneratorInitial(knowledgeBases: _kbs));
  }
}