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}) {
    // Stage-based scaling for enemy stats is removed to simplify balancing.
    // Enemy stats are now fixed as defined in the EnemyTemplate.

    final character = Character(
      name: name,
      maxHp: baseHp,
      atk: baseAtk,
      baseDefense: baseDefense,
      armor: 0,
      image: image,
    );

    // Equip items
    for (final itemId in equipmentIds) {
      final itemTemplate = ItemTable.get(itemId);
      if (itemTemplate != null) {
        // Items no longer scale by stage, pass no stage parameter
        final item = itemTemplate.createItem();
        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();
  }
}
