// enemy_registry.cpp - Implementació del registre estàtic d'enemics
// © 2026 JailDesigner

#include "game/entities/enemy_registry.hpp"

#include <cstdlib>
#include <iostream>
#include <string>

#include "core/entities/entity_loader.hpp"

EnemyConfig EnemyRegistry::pentagon_config;
EnemyConfig EnemyRegistry::square_config;
EnemyConfig EnemyRegistry::pinwheel_config;
EnemyConfig EnemyRegistry::star_config;
EnemyConfig EnemyRegistry::orb_config;
bool EnemyRegistry::loaded = false;

namespace {

    auto loadOne(const std::string& name, EnemyType expected_type, EnemyConfig& out) -> bool {
        auto yaml = Entities::EntityLoader::load(name);
        if (!yaml) {
            std::cerr << "[EnemyRegistry] Error: no s'ha pogut carregar " << name << ".yaml\n";
            return false;
        }
        auto cfg = EnemyConfig::fromYaml(*yaml, expected_type);
        if (!cfg) {
            std::cerr << "[EnemyRegistry] Error: format invàlid a " << name << ".yaml\n";
            return false;
        }
        out = *cfg;
        return true;
    }

}  // namespace

auto EnemyRegistry::loadAll() -> bool {
    const bool OK = loadOne("pentagon", EnemyType::PENTAGON, pentagon_config) &&
        loadOne("square", EnemyType::SQUARE, square_config) &&
        loadOne("pinwheel", EnemyType::PINWHEEL, pinwheel_config) &&
        loadOne("star", EnemyType::STAR, star_config) &&
        loadOne("orb", EnemyType::ORB, orb_config);
    loaded = OK;
    if (OK) {
        std::cout << "[EnemyRegistry] 5 configuracions d'enemic carregades.\n";
    }
    return OK;
}

auto EnemyRegistry::get(EnemyType type) -> const EnemyConfig& {
    if (!loaded) {
        std::cerr << "[EnemyRegistry] FATAL: get() abans de loadAll()\n";
        std::exit(EXIT_FAILURE);
    }
    switch (type) {
        case EnemyType::PENTAGON:
            return pentagon_config;
        case EnemyType::SQUARE:
            return square_config;
        case EnemyType::PINWHEEL:
            return pinwheel_config;
        case EnemyType::STAR:
            return star_config;
        case EnemyType::ORB:
            return orb_config;
    }
    std::cerr << "[EnemyRegistry] FATAL: tipus desconegut\n";
    std::exit(EXIT_FAILURE);
}
