#!/usr/bin/env python

from pip._vendor import requests
from pip._vendor import tomli
import json
import glob
import os

mods = dict()
count = dict()
count["server"] = 0
count["client"] = 0
count["both"] = 0

cache = dict()

class fragile(object):
    class Break(Exception):
      """Break out of the with statement"""

    def __init__(self, value):
        self.value = value

    def __enter__(self):
        return self.value.__enter__()

    def __exit__(self, etype, value, traceback):
        error = self.value.__exit__(etype, value, traceback)
        if etype == self.Break:
            return True
        return error

if os.path.isfile("cache/licenses.json"):
  with open("cache/licenses.json", "r") as f:
    cache = json.load(f)

for mod in glob.glob("pack/mods/*.toml"):
  with open(mod, "r") as f:
    data = tomli.load(f)
    moddata = dict()
    moddata["name"] = data["name"]
    moddata["url"] = ""
    moddata["side"] = data["side"]
    license = dict()

    if "update" in data:
      if "modrinth" in data["update"]:
        id = data["update"]["modrinth"]["mod-id"]
        moddata["id"] = id
        moddata["url"] = "https://modrinth.com/mod/" + id
        moddata["site"] = "Modrinth"

        if id in cache:
          data = cache[id]
        else:
          data = requests.get("https://api.modrinth.com/v2/project/" + id).json()["license"]
          cache[id] = data
        moddata["license"] = data
      elif "curseforge" in data["update"]:
        moddata["url"] = "https://legacy.curseforge.com/projects/" + str(data["update"]["curseforge"]["project-id"])
        moddata["site"] = "CurseForge"

    count[moddata["side"]] += 1
    mods[moddata["name"]] = moddata

with fragile(open("wiki/Modlist.md", "w")) as f:
  if (count["server"] + count["client"] + count["both"]) == 0:
    f.write("## No mods.")
    raise fragile.Break

  f.write("## Total Count\r\n")
  f.write("<table>")
  f.write("\r\n<tr>")
  f.write("<th>Side</th>")
  f.write("<th>Count</th>")
  f.write("</tr>\r\n")

  f.write("<tr>")
  f.write("<td>Total</td>")
  f.write("<td>" + str(count["server"] + count["client"] + count["both"]) + "</td>")
  f.write("</tr>\r\n")

  if count["both"] > 0:
    f.write("<tr>")
    f.write("<td>Shared</td>")
    f.write("<td>" + str(count["both"]) + "</td>")
    f.write("</tr>\r\n")

  if count["client"] > 0:
    f.write("<tr>")
    f.write("<td>Client</td>")
    f.write("<td>" + str(count["client"]) + "</td>")
    f.write("</tr>\r\n")

  if count["server"] > 0:
    f.write("<tr>")
    f.write("<td>Server</td>")
    f.write("<td>" + str(count["server"]) + "</td>")
    f.write("</tr>\r\n")

  f.write("</table>\r\n\r\n")

  f.write("## Individual Mods\r\n")
  f.write("<table>")
  f.write("\r\n<tr>")
  f.write("<th>Name</th>")
  f.write("<th>Side</th>")
  f.write("<th>Link</th>")
  f.write("</tr>\r\n")

  for mod in mods:
    data = mods[mod]
    f.write("\r\n<tr>")
    f.write("<td>" + mod + "</td>")
    f.write("<td>" + data["side"] + "</td>")
    if data["url"] != "":
      f.write("<td><a href=\"" + data["url"] + "\">" + data["site"] + "</a></td>")
    else:
      f.write("<td>N/A</td>")
    f.write("\r\n</tr>")
  f.write("\r\n</table>")

with fragile(open("wiki/Licenses.md", "w")) as f:
  if (count["server"] + count["client"] + count["both"]) == 0:
    f.write("## No mods.")
    raise fragile.Break

  for mod in mods:
    data = mods[mod]
    f.write("## " + mod + "\r\n")
    f.write("<b>")
    if "site" in data and data["site"] == "CurseForge":
      f.write("CurseForge API does not provide license information, see mod page for details.")
    elif "license" in data:
      license = data["license"]
      if license["name"] == "":
        if license["id"] == "LicenseRef-Custom":
          license["name"] = "Custom"
        else:
          license["name"] = license["id"][11:].replace("-", " ")

      if license["url"] != None:
        f.write("<a href=\"" + license["url"] + "\">" + license["name"] + "</a>")
      else:
        f.write(license["name"])
    else:
      f.write("Unknown")
    f.write("</b>\r\n")

if not os.path.exists("cache"):
  os.makedirs("cache")

with open("cache/licenses.json", "w") as f:
  json.dump(cache, f)
