#!/usr/bin/env python3
import os
import fileinput
import re
import sys


modTag = "mod"

file_path_html = 'glife.html'
file_path_mod = 'mods'
file_path_mod_online = 'mods'

data = ''
modData = {}
scripts = {}
dataWithoutModStuff = ''

with open(file_path_html, 'r') as file:
    data = file.read()

dataWithoutModStuff = data

i = 0
regex = r"""<tw-passagedata pid="(\d+)" name="([\s\w]+)" tags="(.*?)" (?:position="\d+,\d+" )?(?:size="\d+,\d+")?>(.*?)</tw-passagedata>"""
for match in re.finditer(regex,data,re.S):
    tags = match.group(3).split()

    if(modTag in tags):
        modId = 'default'
        for tag in tags:
            if tag.startswith('mod_'):
                modId = tag[4:]
        if modId not in modData:
            modData[modId] = ''    
        modData[modId] += match.group(0)+'\n'
        dataWithoutModStuff = dataWithoutModStuff.replace(match.group(0),'')

    i += 1
    if(i % 100 == 0):
        print(i)

regex = r"""/\*\s*Start Mod:\s*"([^"]*)"\s*\*/(.*?)/\*\s*End Mod:\s*"Mod"\s*\*/"""
for match in re.finditer(regex,data,re.S):
    modId = match.group(1).strip()
    if not modId:
        modId = 'default'
    if modId not in scripts:
        scripts[modId] = ''    
    scripts[modId] += match.group(2)
    dataWithoutModStuff = dataWithoutModStuff.replace(match.group(0),'')

for modId, scriptContent in scripts.items():
    if modId not in modData:
        modData[modId] = ''  
    modData[modId] += "\n.-.-.-. STORYDATA / SCRIPT .-.-.-.\n"
    modData[modId] += scriptContent

for modId, modContent in modData.items():
    modPath = os.path.join(file_path_mod,modId+'.html')
    with open(modPath, 'w') as file:
        file.write(modContent)

for modId, modContent in modData.items():
    modPath = os.path.join(file_path_mod_online,modId+'.php')
    with open(modPath, 'w') as file:
        file.write(f'<?php header("Access-Control-Allow-Origin: *"); header(\'Content-type: text/javascript\'); echo($_GET[\'callback\']);?>(`{modContent}\n`);')

with open(file_path_html, 'w') as file:
    file.write(dataWithoutModStuff)

print('Done')