import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/user_profile.dart';
import '../models/preferences.dart';
import '../models/ayuel_response.dart';

class GeminiService {
  GeminiService();

  Future<AyuelResponse> getSuggestion({
    required String transcript,
    required UserProfile profile,
    required AppPreferences prefs,
    required String energyLevel,
    List<Map<String, String>> history = const [],
  }) async {
    try {
      print("🔵 Calling Cloud Function with transcript: $transcript");

      // Inject history into transcript for context awareness
      String finalTranscript = transcript;
      if (history.isNotEmpty) {
        final buffer = StringBuffer();
        buffer.writeln("Previous Conversation Context:");
        for (final turn in history) {
          final label = turn['role'] == 'user' ? 'User' : 'Ayuel';
          buffer.writeln("$label: ${turn['content']}");
        }
        buffer.writeln("\nCurrent User Request: $transcript");
        finalTranscript = buffer.toString();
      }

      // Flatten all data to simple types for Cloud Functions compatibility
      final data = {
        'transcript': finalTranscript,
        'persona': profile.persona ?? '',
        'energyBaseline': profile.energyBaseline ?? '',
        'decisionStyle': profile.decisionStyle ?? '',
        'focusAreas': profile.focusAreas.join(', '),
        'boundariesJson': prefs.boundaries.entries
            .where((e) => e.value)
            .map((e) => e.key)
            .join(', '),
        'gentleNudges': prefs.gentleNudges,
        'focusProtection': prefs.focusProtection,
        'energyLevel': energyLevel,
      };

      print("🔵 Request data: $data");

      // Call Cloud Function via HTTP
      final url = Uri.parse(
        'https://us-central1-heyayuel-7e8b1.cloudfunctions.net/generateAyuelSuggestion',
      );

      final response = await http.post(
        url,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode(data),
      );

      print("🔵 Cloud Function returned: ${response.body}");

      if (response.statusCode != 200) {
        print("🔴 HTTP Error: ${response.statusCode} - ${response.body}");
        throw Exception(
          "HTTP Error: ${response.statusCode} - ${response.body}",
        );
      }

      final jsonMap = jsonDecode(response.body);

      if (jsonMap == null) {
        print("🔴 Empty response from Cloud Function");
        throw Exception("Empty response from Cloud Function");
      }

      final ayuelResponse = AyuelResponse.fromMap(jsonMap);
      print("🔵 Successfully parsed response: ${ayuelResponse.title}");
      return ayuelResponse;
    } catch (e, stackTrace) {
      print("🔴 Gemini/Cloud Function Error: $e");
      print("🔴 Stack trace: $stackTrace");
      // Fallback response
      return AyuelResponse(
        category: "General",
        title: "I'm listening",
        suggestion:
            "I couldn't quite process that. Could you try asking again?",
        why: "My connection seems a bit weak right now.",
        actions: [AyuelAction(label: "Try again", type: "regenerate")],
      );
    }
  }
}

final geminiServiceProvider = Provider<GeminiService>((ref) => GeminiService());
