import 'dart:convert';
import 'package:flutter/services.dart';
import '../model/entity.dart';

import 'item_table.dart';

class EnemyTemplate {
  final String name;
  final int baseHp;
  final int baseAtk;
  final int baseDefense;
  final String? image;
  final List<String> equipmentIds;

  const EnemyTemplate({
    required this.name,
    required this.baseHp,
    required this.baseAtk,
    required this.baseDefense,
    this.image,
    this.equipmentIds = const [],
  });

  factory EnemyTemplate.fromJson(Map<String, dynamic> json) {
    return EnemyTemplate(
      name: json['name'],
      baseHp: json['baseHp'] ?? 10,
      baseAtk: json['baseAtk'] ?? 1,
      baseDefense: json['baseDefense'] ?? 0,
      image: json['image'],
      equipmentIds: (json['equipment'] as List<dynamic>?)?.cast<String>() ?? [],
    );
  }

  Character createCharacter({int stage = 1}) {
    // Simple additive scaling
    int scaledHp = baseHp + (stage - 1) * 5;
    int scaledAtk = baseAtk + (stage - 1);
    int scaledDefense = baseDefense + (stage ~/ 5); // +1 defense every 5 stages

    final character = Character(
      name: name,
      maxHp: scaledHp,
      atk: scaledAtk,
      baseDefense: scaledDefense,
      armor: 0,
      image: image,
    );

    // Equip items
    for (final itemId in equipmentIds) {
      final itemTemplate = ItemTable.get(itemId);
      if (itemTemplate != null) {
        // Create item scaled to stage (optional, currently stage 1)
        // Enemies might get stronger items at higher stages
        final item = itemTemplate.createItem(stage: stage);
        character.addToInventory(item);
        character.equip(item);
      }
    }

    return character;
  }
}

class EnemyTable {
  static List<EnemyTemplate> normalEnemies = [];
  static List<EnemyTemplate> eliteEnemies = [];

  static Future<void> load() async {
    final String jsonString = await rootBundle.loadString(
      'assets/data/enemies.json',
    );
    final Map<String, dynamic> data = jsonDecode(jsonString);

    normalEnemies = (data['normal'] as List)
        .map((e) => EnemyTemplate.fromJson(e))
        .toList();
    eliteEnemies = (data['elite'] as List)
        .map((e) => EnemyTemplate.fromJson(e))
        .toList();
  }
}
