import 'dart:convert';
import 'package:http/http.dart' as http;

class AiRagService {
  static const String _baseUrl =
      'https://n8n-didvan.liara.run/webhook/didvan-rag';
  static const String _authHeader =
      'Basic dXNlcjpkYXNqZHBuM3BjdTQzcDM0aWpyaA==';
  static const String _didvanBaseUrl = 'https://api.didvan.app';

  static String _getFullAudioUrl(String? url) {
    if (url == null || url.isEmpty) return '';

    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url;
    }

    if (url.startsWith('/')) {
      return '$_didvanBaseUrl$url';
    }

    return '$_didvanBaseUrl/$url';
  }

  static Future<AiRagResponse> sendMessage(String message) async {
    try {
      final response = await http.post(
        Uri.parse(_baseUrl),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': _authHeader,
          'Accept': '*/*',
        },
        body: jsonEncode({
          'chatInput': message,
        }),
      );

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        final rawAudioUrl = data['url'] as String?;
        return AiRagResponse(
          output: data['output'] ?? '',
          sources: List<int>.from(data['sources'] ?? []),
          audioUrl: _getFullAudioUrl(rawAudioUrl),
          isSuccess: true,
        );
      } else {
        return AiRagResponse(
          output: 'خطا در دریافت پاسخ از سرور',
          sources: [],
          isSuccess: false,
        );
      }
    } catch (e) {
      return AiRagResponse(
        output: 'خطا در ارتباط با سرور: ${e.toString()}',
        sources: [],
        isSuccess: false,
      );
    }
  }
}

class AiRagResponse {
  final String output;
  final List<int> sources;
  final String? audioUrl;
  final bool isSuccess;

  AiRagResponse({
    required this.output,
    required this.sources,
    this.audioUrl,
    required this.isSuccess,
  });
}
