import os
import json
import random
import subprocess

import flask

from . import core, gamedata, items, jsonizer

rant_env = os.environ.copy()
rant_env["RANT_MODULES_PATH"] = (core.path_appdir / "basepak/rant").as_posix()

## \brief Generates some flavor text.
#  \internal
#
#  This calls the built-in copy of [Rant](https://rant-lang.org) to procedurally generate
#  some flavor text with provided template files.
def generate_flavor_text():
    if core.desktop_mode:
        rant_path = core.path_appdir / "opt/rant/bin/rant"
    else:
        rant_path = "rant" # rely on OS PATH
    flavor_file = gamedata.vfs.copy_out("rant/flavor.rant")
    proc_rant = subprocess.run([rant_path, flavor_file], env=rant_env, capture_output=True)
    return proc_rant.stdout.decode()

class TickEvent(object):
    def __init__(self, tickno, tickweight, tickcode):
        self.tickno = tickno
        self.tickweight = tickweight
        self.tickcode = tickcode

tick_event_list = []
tick_event_list.append(TickEvent(0, 16, "XYZZY"))       # nothing happens
tick_event_list.append(TickEvent(1, 1, "FLAVOR"))       # procedurally generated event of no consequence
tick_event_list.append(TickEvent(10, 2, "ENCHUMAN"))    # encounter: human
tick_event_list.append(TickEvent(11, 2, "ENCGULL"))

## \brief Returns the results of a game tick.
#  \api{GET} /tick
#  \return Game tick events and results.
@core.app.route("/tick")
def tick():
    #return random.choices([json.dumps({"code": 200, "event_type": 0}), json.dumps({"code": 200, "event_type": 1, "log": generate_flavor_text()})], weights=[16, 1])[0]
    ticktypes = []
    tickweights = []

    for event in tick_event_list:
        ticktypes.append(event.tickno) # unce unce unce
        tickweights.append(event.tickweight)

    result = {}
    result["code"] = 200
    result["event_type"] = random.choices(ticktypes, weights=tickweights)[0]

    match result["event_type"]:
        case 0:
            pass
        case 1: # FLAVOR
            result["log"] = generate_flavor_text()
        case 10: # ENCHUMAN
            items_generated = {
                "food": items.generate_item_list("food", "humans", 0, 2),
                "shinies": items.generate_item_list("shinies", "humans", 0, 2)
            }

            if len(items_generated["food"]) < 1 and len(items_generated["shinies"]) < 1:
                # empty item list, force something
                coin_flip = bool(random.getrandbits(1)) #zippy!
                if coin_flip:
                    items_generated["food"] = items.generate_item_list("food", "humans", 1, 3)
                else:
                    items_generated["shinies"] = items.generate_item_list("shinies", "humans", 1, 3)
            result["items"] = items_generated
        case 11: # ENCGULL
            items_generated = {
                "food": items.generate_item_list("food", "humans", 0, 2),
                "shinies": items.generate_item_list("shinies", "humans", 0, 2)
            }

            if len(items_generated["food"]) < 1 and len(items_generated["shinies"]) < 1:
                # empty item list, force something
                coin_flip = bool(random.getrandbits(1)) #zippy!
                if coin_flip:
                    items_generated["food"] = items.generate_item_list("food", "humans", 1, 3)
                else:
                    items_generated["shinies"] = items.generate_item_list("shinies", "humans", 1, 3)
            result["items"] = items_generated
        case _:
            core.log.warning("undefined tick: {0}".format(result["event_type"]))

    return flask.Response(json.dumps(result, cls=jsonizer.JSONizer), status=200, content_type="application/json")

## \brief Returns the results of a colony tick.
#  \api{GET} /tick/colony
#  \return The result of a colony tick.
@core.app.route("/tick/colony", methods=["POST"])
def tick_colony() -> flask.Response:
    req = flask.request.json
    if not req:
        return flask.make_response("Bad request", 400)
    
    colony = req["colony"]
    modifiers = req["modifiers"]
    inc_food = req["avg_food"]
    inc_shinies = req["avg_shinies"]

    out_food = (inc_food * 0.35) * (colony / 2)
    out_shinies = (inc_shinies * 0.25) * (colony / 3)

    result = {
        "success": True,
        "food": out_food,
        "shinies": out_shinies
    }

    return flask.Response(json.dumps(result, cls=jsonizer.JSONizer), status=200, content_type="application/json")
    