import 'package:dio/dio.dart';
import '../../../../core/network/api_endpoints.dart';

class AkinatorResponseModel {
  final String sessionId;
  final String reply;
  final int confidenceScore;
  final Map<String, dynamic>? newsSentiment;
  final Map<String, String> jargonDefinitions;
  final String? memo;
  final String? whatifResult;
  final String? critiqueNote;
  final bool ragUsed;

  const AkinatorResponseModel({
    required this.sessionId,
    required this.reply,
    this.confidenceScore = 0,
    this.newsSentiment,
    this.jargonDefinitions = const {},
    this.memo,
    this.whatifResult,
    this.critiqueNote,
    this.ragUsed = false,
  });

  factory AkinatorResponseModel.fromJson(Map<String, dynamic> json) {
    // Parse jargon_definitions — API sends Map<String, dynamic>
    final rawJargon = json['jargon_definitions'];
    final jargon = <String, String>{};
    if (rawJargon is Map) {
      rawJargon.forEach((k, v) => jargon[k.toString()] = v.toString());
    }

    return AkinatorResponseModel(
      sessionId: (json['session_id'] as String?) ?? '',
      reply: (json['reply'] as String?) ?? '',
      confidenceScore: (json['confidence_score'] as num?)?.toInt() ?? 0,
      newsSentiment: json['news_sentiment'] as Map<String, dynamic>?,
      jargonDefinitions: jargon,
      memo: json['memo'] as String?,
      whatifResult: json['whatif_result'] as String?,
      critiqueNote: json['critique_note'] as String?,
      ragUsed: (json['rag_used'] as bool?) ?? false,
    );
  }

  String? get sentimentLabel {
    if (newsSentiment == null) return null;
    return newsSentiment!['label'] as String?;
  }

  int get sentimentScore {
    if (newsSentiment == null) return 50;
    return (newsSentiment!['score'] as num?)?.toInt() ?? 50;
  }
}

class AkinatorRemoteDatasource {
  final Dio _dio;

  AkinatorRemoteDatasource(this._dio);

  Future<AkinatorResponseModel> predict({
    required String sessionId,
    required String message,
    bool panelMode = false,
    String? knowledgeBaseId,
  }) async {
    final response = await _dio.post(
      ApiEndpoints.akinator,
      data: {
        'session_id': sessionId,
        'message': message,
        'panel_mode': panelMode,
        if (knowledgeBaseId != null) 'knowledge_base_id': knowledgeBaseId,
      },
    );
    return AkinatorResponseModel.fromJson(
        response.data as Map<String, dynamic>);
  }
}