/// AI 性格配置
class AiPersonality {
  final double temperature;
  final List<String> traits;
  final String responseStyle;
  final List<String>? forbiddenTopics;
  final String? model;
  final int? maxTokens;

  const AiPersonality({
    this.temperature = 0.7,
    this.traits = const [],
    this.responseStyle = '',
    this.forbiddenTopics,
    this.model,
    this.maxTokens,
  });

  factory AiPersonality.fromJson(Map<String, dynamic> json) {
    return AiPersonality(
      temperature: (json['temperature'] as num?)?.toDouble() ?? 0.7,
      traits: (json['traits'] as List<dynamic>?)?.cast<String>() ?? [],
      responseStyle: json['response_style'] as String? ?? '',
      forbiddenTopics: (json['forbidden_topics'] as List<dynamic>?)?.cast<String>(),
      model: json['model'] as String?,
      maxTokens: json['max_tokens'] as int?,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'temperature': temperature,
      'traits': traits,
      'response_style': responseStyle,
      if (forbiddenTopics != null) 'forbidden_topics': forbiddenTopics,
      if (model != null) 'model': model,
      if (maxTokens != null) 'max_tokens': maxTokens,
    };
  }
}

/// AI 语音配置
class AiVoiceConfig {
  final String? voiceId;
  final double speed;
  final double pitch;
  final String? emotion;

  const AiVoiceConfig({
    this.voiceId,
    this.speed = 1.0,
    this.pitch = 1.0,
    this.emotion,
  });

  factory AiVoiceConfig.fromJson(Map<String, dynamic> json) {
    return AiVoiceConfig(
      voiceId: json['voice_id'] as String?,
      speed: (json['speed'] as num?)?.toDouble() ?? 1.0,
      pitch: (json['pitch'] as num?)?.toDouble() ?? 1.0,
      emotion: json['emotion'] as String?,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      if (voiceId != null) 'voice_id': voiceId,
      'speed': speed,
      'pitch': pitch,
      if (emotion != null) 'emotion': emotion,
    };
  }
}

/// 角色标签
class CharacterTag {
  final String id;
  final String name;
  final String? color;

  const CharacterTag({
    required this.id,
    required this.name,
    this.color,
  });

  factory CharacterTag.fromJson(Map<String, dynamic> json) {
    return CharacterTag(
      id: json['id'] as String,
      name: json['name'] as String,
      color: json['color'] as String?,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      if (color != null) 'color': color,
    };
  }
}

/// 角色状态枚举
enum CharacterStatus {
  online,
  busy,
  offline;

  static CharacterStatus fromString(String? value) {
    switch (value) {
      case 'online':
        return CharacterStatus.online;
      case 'busy':
        return CharacterStatus.busy;
      case 'offline':
        return CharacterStatus.offline;
      default:
        return CharacterStatus.offline;
    }
  }

  String get value {
    switch (this) {
      case CharacterStatus.online:
        return 'online';
      case CharacterStatus.busy:
        return 'busy';
      case CharacterStatus.offline:
        return 'offline';
    }
  }
}

/// 角色模型
/// 
/// 对应 Supabase 中的 characters 表
class CharacterModel {
  final String id;
  final String name;
  final String? tagline;
  final String? avatarPath;
  final String? description;
  final CharacterStatus status;
  final bool isLocked;
  final bool isActive;
  final int sortOrder;
  
  // AI 配置
  final String? aiSystemPrompt;
  final String? aiGreeting;
  final AiPersonality aiPersonality;
  final AiVoiceConfig aiVoiceConfig;
  
  // 关联的标签
  final List<CharacterTag> tags;
  
  // 时间戳
  final DateTime? createdAt;
  final DateTime? updatedAt;

  const CharacterModel({
    required this.id,
    required this.name,
    this.tagline,
    this.avatarPath,
    this.description,
    this.status = CharacterStatus.offline,
    this.isLocked = false,
    this.isActive = true,
    this.sortOrder = 0,
    this.aiSystemPrompt,
    this.aiGreeting,
    this.aiPersonality = const AiPersonality(),
    this.aiVoiceConfig = const AiVoiceConfig(),
    this.tags = const [],
    this.createdAt,
    this.updatedAt,
  });

  /// 从 JSON 创建（用于 Supabase 响应解析）
  factory CharacterModel.fromJson(Map<String, dynamic> json) {
    // 解析标签 - 可能来自视图的 jsonb 数组或单独查询
    List<CharacterTag> parseTags(dynamic tagsData) {
      if (tagsData == null) return [];
      if (tagsData is List) {
        return tagsData
            .where((t) => t != null && t is Map<String, dynamic>)
            .map((t) => CharacterTag.fromJson(t as Map<String, dynamic>))
            .toList();
      }
      return [];
    }

    return CharacterModel(
      id: json['id'] as String,
      name: json['name'] as String,
      tagline: json['tagline'] as String?,
      avatarPath: json['avatar_path'] as String?,
      description: json['description'] as String?,
      status: CharacterStatus.fromString(json['status'] as String?),
      isLocked: json['is_locked'] as bool? ?? false,
      isActive: json['is_active'] as bool? ?? true,
      sortOrder: json['sort_order'] as int? ?? 0,
      aiSystemPrompt: json['ai_system_prompt'] as String?,
      aiGreeting: json['ai_greeting'] as String?,
      aiPersonality: json['ai_personality'] != null
          ? AiPersonality.fromJson(json['ai_personality'] as Map<String, dynamic>)
          : const AiPersonality(),
      aiVoiceConfig: json['ai_voice_config'] != null
          ? AiVoiceConfig.fromJson(json['ai_voice_config'] as Map<String, dynamic>)
          : const AiVoiceConfig(),
      tags: parseTags(json['tags']),
      createdAt: json['created_at'] != null
          ? DateTime.parse(json['created_at'] as String)
          : null,
      updatedAt: json['updated_at'] != null
          ? DateTime.parse(json['updated_at'] as String)
          : null,
    );
  }

  /// 转换为 JSON（用于插入/更新）
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'tagline': tagline,
      'avatar_path': avatarPath,
      'description': description,
      'status': status.value,
      'is_locked': isLocked,
      'is_active': isActive,
      'sort_order': sortOrder,
      'ai_system_prompt': aiSystemPrompt,
      'ai_greeting': aiGreeting,
      'ai_personality': aiPersonality.toJson(),
      'ai_voice_config': aiVoiceConfig.toJson(),
    };
  }

  /// 获取标签名称列表（用于兼容旧代码）
  List<String> get tagNames => tags.map((t) => t.name).toList();

  /// 复制并修改部分字段
  CharacterModel copyWith({
    String? id,
    String? name,
    String? tagline,
    String? avatarPath,
    String? description,
    CharacterStatus? status,
    bool? isLocked,
    bool? isActive,
    int? sortOrder,
    String? aiSystemPrompt,
    String? aiGreeting,
    AiPersonality? aiPersonality,
    AiVoiceConfig? aiVoiceConfig,
    List<CharacterTag>? tags,
  }) {
    return CharacterModel(
      id: id ?? this.id,
      name: name ?? this.name,
      tagline: tagline ?? this.tagline,
      avatarPath: avatarPath ?? this.avatarPath,
      description: description ?? this.description,
      status: status ?? this.status,
      isLocked: isLocked ?? this.isLocked,
      isActive: isActive ?? this.isActive,
      sortOrder: sortOrder ?? this.sortOrder,
      aiSystemPrompt: aiSystemPrompt ?? this.aiSystemPrompt,
      aiGreeting: aiGreeting ?? this.aiGreeting,
      aiPersonality: aiPersonality ?? this.aiPersonality,
      aiVoiceConfig: aiVoiceConfig ?? this.aiVoiceConfig,
      tags: tags ?? this.tags,
      createdAt: createdAt,
      updatedAt: updatedAt,
    );
  }
}
