#include <catch2/catch_test_macros.hpp>
#include <iostream>
#include <set>
#include "combat/battle.hpp"
#include "algos/simplefsm.hpp"
#include "algos/dinkyecs.hpp"
#include "gui/backend.hpp"
#include "game/level.hpp"
#include "game/components.hpp"
#include "ai/ai.hpp"
#include "graphics/palette.hpp"

using namespace combat;
using namespace components;

TEST_CASE("battle operations fantasy", "[combat-battle]") {
  ai::reset();
  ai::init("ai");

  auto ai_start = ai::load_state("Enemy::initial_state");
  auto ai_goal = ai::load_state("Enemy::final_state");
  auto host_start = ai::load_state("Host::initial_state");
  auto host_goal = ai::load_state("Host::final_state");
  BattleEngine battle;

  DinkyECS::Entity host = 0;
  ai::EntityAI host_ai("Host::actions", host_start, host_goal);
  components::Combat host_combat{.max_hp=50, .ap_delta=6, .max_ap=12, .damage=20};
  battle.add_enemy({host, &host_ai, &host_combat, true});

  DinkyECS::Entity axe_ranger = 1;
  ai::EntityAI axe_ai("Enemy::actions", ai_start, ai_goal);
  components::Combat axe_combat{.max_hp=50, .ap_delta=8, .max_ap=12, .damage=20};
  battle.add_enemy({axe_ranger, &axe_ai, &axe_combat});

  DinkyECS::Entity rat = 2;
  ai::EntityAI rat_ai("Enemy::actions", ai_start, ai_goal);
  components::Combat rat_combat{.max_hp=50, .ap_delta=2, .max_ap=10, .damage=10};
  battle.add_enemy({rat, &rat_ai, &rat_combat});

  battle.set_all("enemy_found", true);
  battle.set_all("in_combat", true);
  battle.set_all("tough_personality", true);
  battle.set_all("health_good", true);

  battle.set(rat, "tough_personality", false);
  battle.set(host, "have_healing", false);
  battle.set(host, "tough_personality", false);

  while(!host_combat.is_dead()) {
    battle.set(host, "health_good", host_combat.almost_dead());

    battle.player_request("use_healing");
    battle.player_request("kill_enemy");

    battle.ap_refresh();
    battle.plan();

    while(auto act = battle.next()) {
      auto& [enemy, wants_to, cost, enemy_state] = *act;

      switch(enemy_state) {
        case BattleHostState::agree:
          // fmt::println("HOST and PLAYER requests match {}, doing it.", wants_to);
          break;
        case BattleHostState::disagree:
          // fmt::println("REBELIOUS ACT: {}", wants_to);
          battle.clear_requests();
          REQUIRE(battle.$player_requests.size() == 0);
          break;
        case BattleHostState::not_host:
         if(wants_to == "kill_enemy") {
          enemy.combat->attack(host_combat);
         }
         break;
        case BattleHostState::out_of_ap:
         // fmt::println("ENEMY OUT OF AP");
         break;
      }
    }

    REQUIRE(!battle.next());
  }
}
