import sys
from url_mappings import *
from pathlib import Path

selected_mode = (sys.argv[1] if len(sys.argv) >= 2 else None)

source_path = "source/general-information.md"
output_paths = {"readme": "../README.md", "doc": "preprocessed/general-information.md", "manual": "build/latex/user-manual.md"}
replace_in_doc = {""}
for mode in output_paths.keys():
	if selected_mode is not None and mode != selected_mode:
		continue
	with open(source_path, "r") as f_in:
		Path("/".join(output_paths[mode].split("/")[:-1])).mkdir(parents=True, exist_ok=True)
		with open(output_paths[mode], "w") as f_out:
			current_condition_mode = None # Tracks the condition of the current if-else statement we're in
			current_condition_excluded_modes = [] # Tracks which modes were already handled by earlier if-clauses and need to be excluded now
			for line in f_in.readlines():
				if line.startswith("IFMODEIS"):
					if current_condition_mode is not None:
						raise Exception("This parser does not support nested conditions!")
					_, current_condition_mode = line.strip().split(" ")
					current_condition_excluded_modes = []
				elif line.startswith("ELSE"):
					if current_condition_mode is None:
						raise Exception("Encountered ELSE without IFMODEIS!")
					current_condition_excluded_modes.append(current_condition_mode)
					if line.startswith("ELSE IFMODEIS"):
						_, _, current_condition_mode = line.strip().split(" ")
					else:
						current_condition_mode = None
				elif line.startswith("ENDIF"):
					if current_condition_mode is None and len(current_condition_excluded_modes) == 0:
						raise Exception("Encountered ENDIF without IFMODEIS!")
					current_condition_mode = None
					current_condition_excluded_modes = []
				else:
					if (current_condition_mode is None or current_condition_mode == mode) and mode not in current_condition_excluded_modes:
						# Line is included, optionally apply some more transformations
						line = apply_url_mappings(line)
						if mode == "doc":
							# Change hyperlinks to local references
							match_string = "(https://people.cs.kuleuven.be/~wouter.baert/atc/doc/"
							pos = 0
							while True:
								pos = line.find(match_string, pos)
								if pos == -1:
									break
								parenthesis_pos = line.find(")", pos)
								# Remove matched string and replace it with ": <", remove closing parenthesis and replace it with ">"
								internal_path = line[pos + len(match_string):parenthesis_pos]
								replace_string = "(" + internal_path + ")"
								line = line[:pos] + replace_string + line[parenthesis_pos + 1:]
						f_out.write(line)
