import 'package:flutter/foundation.dart';
import '../services/supabase_service.dart';
import '../models/character_model.dart';
import '../models/category_model.dart';

/// 角色仓库
/// 
/// 负责从 Supabase 获取角色相关数据
class CharacterRepository {
  CharacterRepository._();

  /// 获取所有分类
  static Future<List<CategoryModel>> getCategories() async {
    try {
      final response = await SupabaseService.from('categories')
          .select()
          .eq('is_active', true)
          .order('sort_order', ascending: true);
      
      return (response as List)
          .map((json) => CategoryModel.fromJson(json))
          .toList();
    } catch (e) {
      debugPrint('❌ 获取分类失败: $e');
      rethrow;
    }
  }

  /// 获取所有角色（包含标签）
  /// 
  /// 使用 characters_with_tags 视图获取完整数据
  static Future<List<CharacterModel>> getCharacters() async {
    try {
      final response = await SupabaseService.from('characters_with_tags')
          .select();
      
      return (response as List)
          .map((json) => CharacterModel.fromJson(json))
          .toList();
    } catch (e) {
      debugPrint('❌ 获取角色列表失败: $e');
      rethrow;
    }
  }

  /// 根据分类筛选角色
  /// 
  /// [categoryCode] 分类代码，如 'gentle', 'dom' 等
  /// 'all' 返回所有角色
  static Future<List<CharacterModel>> getCharactersByCategory(String categoryCode) async {
    try {
      // 如果是 'all'，直接获取所有
      if (categoryCode == 'all') {
        return getCharacters();
      }

      // 获取该分类下的标签
      final tagsResponse = await SupabaseService.from('tags')
          .select('name')
          .eq('category_id', 
              SupabaseService.from('categories')
                  .select('id')
                  .eq('code', categoryCode)
                  .single()
          );

      final tagNames = (tagsResponse as List)
          .map((t) => t['name'] as String)
          .toList();

      if (tagNames.isEmpty) {
        return [];
      }

      // 获取包含这些标签的角色
      final allCharacters = await getCharacters();
      
      return allCharacters.where((char) {
        return char.tagNames.any((tag) => tagNames.contains(tag));
      }).toList();
    } catch (e) {
      debugPrint('❌ 按分类获取角色失败: $e');
      // 如果查询失败，返回本地筛选
      return _filterCharactersLocally(await getCharacters(), categoryCode);
    }
  }

  /// 本地筛选角色（作为后备方案）
  static List<CharacterModel> _filterCharactersLocally(
    List<CharacterModel> characters, 
    String categoryCode
  ) {
    if (categoryCode == 'all') return characters;
    
    return characters.where((c) {
      final tags = c.tagNames.join('');
      switch (categoryCode) {
        case 'gentle':
          return tags.contains('治愈') || tags.contains('温顺') || tags.contains('医疗');
        case 'dom':
          return tags.contains('强势') || tags.contains('调教') || tags.contains('指令');
        case 'wild':
          return tags.contains('病娇') || tags.contains('神秘') || 
                 tags.contains('不稳定') || tags.contains('极乐');
        case 'exclusive':
          return c.isLocked;
        default:
          return false;
      }
    }).toList();
  }

  /// 根据 ID 获取单个角色
  static Future<CharacterModel?> getCharacterById(String id) async {
    try {
      final response = await SupabaseService.from('characters_with_tags')
          .select()
          .eq('id', id)
          .maybeSingle();
      
      if (response == null) return null;
      return CharacterModel.fromJson(response);
    } catch (e) {
      debugPrint('❌ 获取角色详情失败: $e');
      rethrow;
    }
  }

  /// 获取角色头像的公开 URL
  /// 
  /// [avatarPath] Storage 中的路径
  static String getAvatarUrl(String? avatarPath) {
    if (avatarPath == null || avatarPath.isEmpty) {
      // 返回默认头像
      return 'https://via.placeholder.com/300x400?text=No+Avatar';
    }
    
    // 如果已经是完整 URL，直接返回
    if (avatarPath.startsWith('http')) {
      return avatarPath;
    }
    
    // 从 Storage 获取公开 URL
    return SupabaseService.storage
        .from('avatars')
        .getPublicUrl(avatarPath);
  }

  /// 获取仅会员可见的角色
  static Future<List<CharacterModel>> getLockedCharacters() async {
    try {
      final response = await SupabaseService.from('characters_with_tags')
          .select()
          .eq('is_locked', true);
      
      return (response as List)
          .map((json) => CharacterModel.fromJson(json))
          .toList();
    } catch (e) {
      debugPrint('❌ 获取会员角色失败: $e');
      rethrow;
    }
  }
}
