#ifndef SERVER
#include <stdint.h>
#include <stdbool.h>
#include "common.hpp"
#include <cstring>
#include <filesystem>
#include "yaml-cpp/yaml.h"
#include <iostream>
#include <regex>

#include <string>
#include <regex>
#include <iostream>

static std::map<std::string, std::regex> tags = {};

static bool ParseRecipe(const std::string &s, RecipeItem &out) {
    static const std::regex re(R"(^([^:]+):([^*]+)(?:\*([0-9]+))?$)");
    std::smatch m;
    if (!std::regex_match(s, m, re)) return false;
    if(m[1].str() == "block")
        out.type = IType_Block;
    else if(m[1].str() == "tag")
        out.type = IType_Special_Tag;
    else
        out.type = IType_Generic;
    out.id = m[2].str();
    if (m[3].matched) out.quantity = std::stoi(m[3].str());
    else out.quantity = 1;
    return true;
}

bool IDTagMatch(std::string tag, std::string id) {
    std::smatch m;
    std::cout << tag << std::endl;
    std::cout << id << std::endl;
    return std::regex_match(id, m, tags[tag]);
}
std::list<Recipe> recipes;

void LoadRecipes() {
    tags["planks"] = std::regex(".*planks$");
    std::vector<std::filesystem::path> recipeList;
    recipeList.clear();
    std::cout << "A" << std::endl;
    std::filesystem::path recipes_path{Pathify("recipes")};
    std::cout << "A" << std::endl;
    for (auto const& dir_entry : std::filesystem::directory_iterator{recipes_path}) {
        try
        {
            Recipe _recipe;
            const std::string path = dir_entry.path().u8string();
            std::cout << "loading " << path << std::endl;
            YAML::Node recipe = YAML::LoadFile(path);
            _recipe.requiredStation = recipe["station"].as<std::string>();
            for (auto s : recipe["inputs"]) {
                RecipeItem r;
                if (ParseRecipe(s.as<std::string>(), r)) {
                    _recipe.inputs.push_back(r);
                } else {
                    std::cout << "parse failed for: " << s << std::endl;
                }
            }
            for (auto s : recipe["outputs"]) {
                RecipeItem r;
                if (ParseRecipe(s.as<std::string>(), r)) {
                    _recipe.outputs.push_back(r);
                } else {
                    std::cout << "parse failed for: " << s << std::endl;
                }
            }
            recipes.push_back(_recipe);
        }
        catch(const std::exception& e)
        {
            std::cerr << "Exception while loading recipe " << dir_entry << ": "<< e.what() << '!' << std::endl;
        }
    }
}

#endif