#!/usr/bin/env python3

import os
from glob import glob
import fileinput
import re
import sys
def file_convert(filename):
	global tw_sources_path, tw_destination_path
	source_filepath= os.path.join(tw_sources_path,filename)+'.tw'
	destination_filepath= os.path.join(tw_destination_path,filename)+'compiled.js'
	with open(source_filepath, 'r') as file:
		lines = [line.rstrip() for line in file]

	npccounter = 0

	with open(destination_filepath, 'w') as file:
		file.write("setup.npcs ??= {};\n")
		identifier = 'none'
		npc_id = ''
		npc_subobjects = {}
		npc_defaults = []
		counter = 0
		for line in lines:
			line = line.strip()
			if match := re.match(r"""<<set\s+\$npctemp\s*=\s*(\d+)>>""",line):
				if len(npc_id) > 0:


					for npc_subobject_id in npc_subobjects:
						npc_subobject = npc_subobjects[npc_subobject_id]
						file.write('\t'+npc_subobject_id+':{\n')
						for valueKey in npc_subobject:
							val = npc_subobject[valueKey]
							file.write('\t\t'+valueKey+':'+val+',\n')

						file.write('\t},\n')

						if len(npc_defaults) > 0:
							file.write('\tdefaults:[')
							file.write(','.join(npc_defaults))
							file.write('],\n')


					file.write('}\n')

				npc_id = 'A'+match.group(1)
				npc_subobjects = {}
				npc_defaults = []
				file.write('setup.npcs["'+npc_id+'"] = {\n')
			elif len(npc_id) > 0:
				if match := re.match(r"""<<set(?:init)?\s+\$(npc_)?(\w*?)\[\s*'A'\s*\+\s*\$npctemp\s*(?:\+\s*'(\w+)')?\]\s*=\s*(.*?)\s*>>""",line):
					if match.group(3):
						subObjectName = match.group(3)
						if subObjectName.startswith('_'):
							subObjectName = subObjectName[1:]
						if not match.group(2) in npc_subobjects:
							npc_subobjects[match.group(2)] = {}
						npc_subobjects[match.group(2)][subObjectName] = match.group(4)
					else:
						v = match.group(4)
						if v.startswith('$') or v.startswith('(') or v[0].isalpha():
							v="'Incorrect Initialization: "+v+"'"
						file.write('\t')
						file.write(match.group(2))
						file.write(':')
						file.write(v)
						file.write(',\n')
				elif match := re.match(r"""<<run \$npcs\.set\('A' \+ \$npctemp,'([^']+)',(.*)\)>>""",line): # Plain values
					field = match.group(1)
					v = match.group(2)

					if "rand(" in v or v[0] == '$':
						v = "'Incorrect Initialization: "+v+"'"

					if field == 'firstname':
						firstname = v

					if field == 'usedname' and v == firstname:
						continue

					file.write('\t')
					file.write(field)
					file.write(':')
					file.write(v)
					file.write(',\n')
				elif match := re.match(r"""<<run \$npcs\.set\('A'\+\$npctemp\+'(\w+)','(\w+)',([^>]+)\)>>""",line): # Subarrays, such as preferences
					subObjectName = match.group(1)
					if subObjectName.startswith('_'):
						subObjectName = subObjectName[1:]
					if not match.group(2) in npc_subobjects:
						npc_subobjects[match.group(2)] = {}
					npc_subobjects[match.group(2)][subObjectName] = match.group(3)
				elif match := re.match(r"""<<setinit \$pc\.hotcat_rating\['A' \+ \$npctemp\] = (\d+)>>""",line): # Hotcat
					v = match.group(1)
					file.write('\t')
					file.write('hotcat_rating:')
					file.write(v)
					file.write(',\n')
				elif match:= re.match(r"""<<gs 'npcstaticdefaults'\s*(.*?)>>""",line,re.I):
					npc_defaults.append(match.group(1).replace("' '",'_'))


		for npc_subobject_id in npc_subobjects:
			npc_subobject = npc_subobjects[npc_subobject_id]
			file.write('\t'+npc_subobject_id+':{\n')
			for valueKey in npc_subobject:
				val = npc_subobject[valueKey]
				file.write('\t\t'+valueKey+':'+val+',\n')

			file.write('\t},\n')

			if len(npc_defaults) > 0:
				file.write('\tdefaults:[')
				file.write(','.join(npc_defaults))
				file.write('],\n')

		file.write('}\n')




tw_sources_path = os.path.join("sugarcube","src","npcs","_npcstatic")
tw_destination_path = os.path.join(tw_sources_path,"compiled")

os.makedirs(tw_destination_path,exist_ok=True)

filesNames = [y for x in os.walk(tw_sources_path) for y in glob(os.path.join(x[0], '*.tw'))]
#print(filesNames)
for file in filesNames:
	#print(file)
	file_convert(os.path.basename(file).split('.')[0])
