# Publish the output of `build.py`
# as a Gitea package.

from pathlib import Path
import requests
import json
import os
import re

URL = "https://git.betalupi.com"
USER = os.environ["PUBLISH_USER"]
PACKAGE = os.environ["PACKAGE"]
VERSION = os.environ["VERSION"]
AUTH = requests.auth.HTTPBasicAuth(USER, os.environ["PUBLISH_KEY"])

ROOT: Path = Path(os.getcwd())
SRC_DIR: Path = ROOT / "output"


def log(msg):
	print(f"[PUBLISH.PY] {msg}")


log(f"Version is {VERSION}")
log(f"Package is {PACKAGE}")
log(f"Running in {ROOT}")
if not ROOT.is_dir():
	log("Root is not a directory, cannot continue")
	exit(1)

log(f"Source dir is {SRC_DIR}")
if not SRC_DIR.exists():
	log("Source dir doesn't exist, cannot continue")
	exit(1)


def del_package():
	log(f"Deleting package {PACKAGE}/{VERSION}")
	res = requests.delete(
		f"{URL}/api/packages/{USER}/generic/{PACKAGE}/{VERSION}",
		auth=AUTH,
	)
	if res.status_code != 204 and res.status_code != 404:
		log(f"Deletion failed with code {res.status_code}")


# Delete if already exists
# (important for the `latest` package)
del_package()


def upload(data, target: str):
	target = re.sub("[^A-Za-z0-9_. -]+", "", target)

	res = requests.put(
		f"{URL}/api/packages/{USER}/generic/{PACKAGE}/{VERSION}/{target}",
		auth=AUTH,
		data=data,
	)

	if res.status_code != 201:
		log(f"Upload failed with code {res.status_code}")
		del_package()  # Do not keep partial package if upload fails
		exit(1)

	return f"{URL}/api/packages/{USER}/generic/{PACKAGE}/{VERSION}/{target}"


index_file = SRC_DIR / "index.json"
with index_file.open("r") as f:
	index = json.load(f)

new_index = []
for handout in index:
	title = handout["title"]
	group = handout["group"]
	h_file = SRC_DIR / handout["handout_file"]
	s_file = handout["solutions_file"]
	if s_file is not None:
		s_file = SRC_DIR / s_file
	log(f"Uploading {title}")

	h_url = None
	s_url = None

	h_url = upload(h_file.open("rb").read(), f"{group} - {title}.pdf")
	if s_file is not None:
		log(f"Uploading {title} solutions")
		s_url = upload(s_file.open("rb").read(), f"{group} - {title}.sols.pdf")

	new_index.append(
		{"title": title, "group": group, "handout": h_url, "solutions": s_url}
	)

upload(json.dumps(new_index), "index.json")
