from modules.DB import UseDB
from loguru import logger
import random
import configparser


def get_random_event():
    db = UseDB("events")
    response = db.find_document({})
    random_event = random.choices([i["_id"] for i in response],
                                  weights=[i["probability"] for i in response])
    return db.find_document({"_id": random_event[0]})[0]


def recalculation_events(well):
    difficulties = {
        "Простая": [5, 5],
        "Средняя": [5, 2],
        "Сложная": [5, 1],
        "Проигрывать весело": [10, 1]
    }
    config = configparser.ConfigParser()
    config.read("conf/config.ini")
    difficulty = config['Settings']['difficulty']
    db = UseDB("events")
    not_well_events = db.find_document({"well": False})
    well_events = db.find_document({"well": True})
    if well:
        for i in not_well_events:
            db.update_document({"_id": i["_id"]},
                               {"probability": i["probability"] + difficulties[difficulty][0]})
        ratio = len(not_well_events) * difficulties[difficulty][0] / len(well_events)
        for i in well_events:
            db.update_document({"_id": i["_id"]}, {"probability": i["probability"] - ratio})
    else:
        for i in well_events:
            db.update_document({"_id": i["_id"]},
                               {"probability": i["probability"] + difficulties[difficulty][1]})
        ratio = len(well_events) * difficulties[difficulty][1] / len(not_well_events)
        for i in not_well_events:
            db.update_document({"_id": i["_id"]}, {"probability": i["probability"] - ratio})


def start_calculating():
    logger.debug("Валидация началась")
    db = UseDB("events")
    response = db.find_document({})
    sum_percent_probability = sum([i["probability"] for i in response])
    sum_percent_probability_in_events = sum([sum(i["probability_consequence"]) for i in response])
    if sum_percent_probability != 100:
        logger.critical("Сумма вероятностей всех ивентов не равна 100, это плохо, не надо так")
        quit(0)
    if sum_percent_probability_in_events != len(response) * 100:
        logger.critical("Проблема в каком-то ивенте, сумма вероятностей не правильная")
        quit(0)
    for i in response:
        if not (len(i["variants"]) == len(i["consequence"]) == len(i["probability_consequence"])):
            logger.critical(f"Ошибка в ивенте {i['name']}. Разница в длинах variants, consequence "
                            f"и probability_consequence")
            quit(0)
    logger.debug("Валидация игры успешно прошла")
