import sys
import XMLParse.XMLParser as XMLParser
import logging
import ASTTypes.ASTNode
from Utils.utilities import *
import os


def main(files: list[str], *args, **kwargs) -> list[tuple[str, ASTTypes.ASTNode.ASTNode]]:
    ret: list[tuple[str, ASTTypes.ASTNode.ASTNode]] = []
    for file in files:
        AST = XMLParser.parse_pdom_file(file)
        logging.debug("AST printout\n" + AST.dump_tree())
        ret.append((file, AST))
    return ret


if __name__ == "__main__":
    argv = sys.argv[1:]
    options_parsed = False
    options = {}
    while not options_parsed:
        match argv:
            case ["--debug" | "-d", *rest]:
                logging.basicConfig(level=logging.DEBUG)
                argv = rest
            case ["--save-trees" | "-s", *rest]:
                options["save-trees"] = True
                argv = rest
            case ["--translate" | "-t", *rest]:
                options["translate"] = True
                argv = rest
            case ["--ascii-force", *rest]:
                argv = rest
                import ASTTypes.ASTNode as ast_node
                ast_node.ascii_force = True
            case []:
                logging.critical(f"No files specified! Quitting")
                exit(99)
            case [*files]:
                options["files"] = files
                options_parsed = True

    logging.info(f"Starting analysis")
    ast_s = main(**options)

    if options.get('save-trees', False):
        logging.info(f"'--save-trees': Saving trees is now enabled.")
        for file, ast in ast_s:
            outpath = os.path.splitext(file)[0]
            outpath += ".ast"
            logging.info(f'Opening file {outpath}')
            with open(outpath, mode='w', encoding='utf-8') as outfile:
                logging.info(f'Writing AST to file {outpath}')
                outfile.write(ast.dump_tree())

    if options.get('translate', False):
        for file, ast in ast_s:
            translation = ast.translate()
            logging.debug(f"Translation of {file}:\n{translation}")
            outpath = os.path.splitext(file)[0] + ".js"
            logging.info(f"Writing file {outpath}")
            with open(outpath, mode="w", encoding="utf-8") as outfile:
                outfile.write(translation)
                outfile.write("\n\n\n\n// Compatibility functions\n")
                outfile.write("function print(...args){\n\tfor (var arg of args){\n\t\t"
                              "process.stdout.write(arg.toString())\n\t}\n}")


