import 'package:flutter/foundation.dart';
import '../network/api_client.dart';

/// AI 聊天服务
class AiChatService {
  final ApiClient _apiClient;

  AiChatService({ApiClient? apiClient})
      : _apiClient = apiClient ?? ApiClient.instance;

  /// 发送消息并获取AI回复
  Future<AiChatResponse> sendMessage(String message, {String? context}) async {
    try {
      final body = <String, dynamic>{'message': message};
      if (context != null) body['context'] = context;

      final response = await _apiClient.post('/api/v1/ai/chat', data: body);
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return AiChatResponse.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[AiChatService] sendMessage 失败: $e');
      rethrow;
    }
  }

  /// 获取AI定价建议
  Future<Map<String, dynamic>> getPricingSuggestion({
    required double faceValue,
    String? category,
  }) async {
    try {
      final response = await _apiClient.post('/api/v1/ai/pricing/suggest', data: {
        'faceValue': faceValue,
        if (category != null) 'category': category,
      });
      final data = response.data is Map<String, dynamic> ? response.data : {};
      return (data['data'] ?? data) as Map<String, dynamic>;
    } catch (e) {
      debugPrint('[AiChatService] getPricingSuggestion 失败: $e');
      rethrow;
    }
  }
}

class AiChatResponse {
  final String message;
  final String? intent;
  final Map<String, dynamic>? metadata;

  const AiChatResponse({
    required this.message,
    this.intent,
    this.metadata,
  });

  factory AiChatResponse.fromJson(Map<String, dynamic> json) {
    return AiChatResponse(
      message: json['message'] ?? json['reply'] ?? '',
      intent: json['intent'],
      metadata: json['metadata'] as Map<String, dynamic>?,
    );
  }
}
