import os
import sys
import regex
import subprocess
import argparse
import glob

from valeptex.valeptex import *




def valep_parse_latex_store_html(tex_file_name, stack):
    
    # remove file ending .tex if applicable
    if tex_file_name[-4:] == '.tex':
        tex_file_name = tex_file_name[0:-4]

    # call main function parse_latex
    html_content, stack = parse_latex(tex_file_name, stack)



    # Write rendered file to a .html file
    temp_tex_file_name = f'{tex_file_name}.{stack.output_format}'
    try:
        with open(temp_tex_file_name, 'w', encoding='utf-8') as f:
            f.write(html_content)
    except: 
        print(f'ERROR: could not write {temp_tex_file_name}!')

    undefined = stack.expand_unknown()
    #print(undefined)

    # Write stack content and errors to a .log file
    #temp_tex_file_name = tex_file_name + '.log'
    #with open(temp_tex_file_name, 'w', encoding='utf-8') as f:
    #    f.write(stack.expand())
    #    f.write('\n\nERROR list:\n')
    #    f.write(error)

    return stack


# special function of the Carnap edition project:
# splits all diary chapters in the current folder in snippets that contain only a single entry
def convert_tex_to_diary_snippets():
    chapters = ['01']
    i=1
    while i < 74:
        i += 1
        if i < 10:
            chapters.append(f'0{i}')
        else:
            chapters.append(f'{i}')
    
    path = os.path.dirname(os.path.abspath(__file__)) + '/carnap-layout.jinja2'
    with open(path, 'r', encoding='utf-8', newline='') as template:
        html_template = template.read()
    html_template = regex.sub('<div class="table-of-content">','<div class="table-of-content" style="display:none">',html_template)
    html_template = regex.sub('<button class="button" style="width:130px" title="Download: Not Yet Implemented">', '<button class="button" style="width:130px;visibility:hidden;" title="Download: Not Yet Implemented">', html_template)
    i = html_template.find(r'{{ obj }}')
    html_template_begin = html_template[0:i]
    html_template_end = html_template[i+9:len(html_template)]
    for chpt in chapters: 
        try:
            with open(f'{chpt}.html', 'r', encoding='utf-8', newline='') as file:
                html_content = file.read()
            print(f'... processing diary entries from file {chpt}.html')
            html_template_header = regex.search('<h1.*?</h1>',html_content)[0]
            html_template_header = html_template_header[0:len(html_template_header)-5]
            html_template_begin = regex.sub('<a class="chapterup" href=".*">',f'<a class="chapterup" href="../../{chpt}.html">',html_template_begin,1)
            snippets = html_content.split('<time class="diary-entry"')
            for snippet in snippets:
                i = snippet.find('<p class="diary">')
                if i > 0:
                    snippet = snippet[0:i]
                snippet = '<p class="diary"><time class="diary-entry"' + snippet
                i = snippet.find('</td')
                if i > 0 and (snippet[0:i].find('<td>') == -1):
                    snippet = snippet[0:i]
                i = snippet.find('<p><table class="nest"')
                if i > 0:
                    snippet = snippet[0:i]
                i = snippet.find('<end-diary-entry>')
                date = regex.search(r'datetime="(.*?)"',snippet)
                if date:
                    nicedate = nice_date(date.group(1))
                    snippet = f'{html_template_begin}<a class="chapterfile" href="../../{chpt}.html">{html_template_header}, Eintrag {nicedate}</h1></a>\n\n{snippet}{html_template_end}'
                    dat = date.group(1).split('-')[0]
                    if not os.path.exists(f'entries/{dat}'):
                        os.makedirs(f'entries/{dat}')
                    with open(f'entries/{dat}/entry-{date.group(1)}.html', 'w', encoding='utf-8', newline='') as f:
                        f.write(snippet)
        except:
            print(f'ERROR while processing diary entries: File {chpt}.html could not be processed!')    
    print('DONE.')



# batch processing of parse_latex: either convert all .tex files in the current folder or
# in the current folder together with all its subfolders ::: options --folder and --subfolders

def convert_folder_tex_to_html(folder_path, stack, include_subfolders=False):
    # it does not convert any file that is listed in excludefiles or ends with _temp.tex or _internal.tex
    excludefiles = {'abbildungen_1.tex', 
                    'abbildungen_2.tex',
                    'colorhook.tex',
                    'befehle.tex',
                    'befehleetx.tex',
                    'hyphenation.tex',
                    'institutionen_definitionen.tex',
                    'literatur_herausgeber.tex',
                    'literatur_herausgeber_band_drei.tex',
                    'markup.tex',
                    'namen_definitionen.tex',
                    'namen_querverweise.tex',
                    'namen_querverweise_band_eins.tex',
                    'namen_querverweise_band_zwei.tex',
                    'namen_querverweise_band_drei.tex',
                    'namen_querverweise_band_vier.tex',
                    'namen_querverweise_briefe_band_zwei.tex',
                    'werke_anderer_definitionen.tex',
                    'werke_carnaps_definitionen.tex'
                    }
    pattern = os.path.join(folder_path, '**/*.tex') if include_subfolders else os.path.join(folder_path, '*.tex')
    error = ""
    for tex_file in glob.iglob(pattern, recursive=True):
        # change to subdir
        directory = os.path.dirname(tex_file)
        os.chdir(directory)
        # use relativ filepath (absolute may not work for plastex
        tex_file = os.path.relpath(tex_file)  
        if not tex_file in excludefiles:
            
            #stack = valep_parse_latex_store_html(tex_file, stack)

            try:
                stack = valep_parse_latex_store_html(tex_file, stack)
            except: 
                print(f"ERROR: conversion of file {tex_file} failed.")
                error += f"ERROR: conversion of file {tex_file} failed."

    write_log(stack)




if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Parse LaTeX")
    parser.add_argument("tex_file", nargs="?", help="Path to the .tex file to convert")
    parser.add_argument("--folder", action="store_true", help="Convert .tex files in the current folder")
    parser.add_argument("--subfolders", action="store_true", help="Convert .tex files in all subfolders")
    parser.add_argument("--entries", action="store_true", help="Convert diary files to diary snippets")
    parser.add_argument("--normalize", action="store_true", help="save also a .txt version of the document")
    parser.add_argument("--nologfile", action="store_true", help="do not save the valeptex.log")
    parser.add_argument("--writeunknown", action="store_true", help="only write the unknown commands in the logfile")
    parser.add_argument("--useownpreamble", action="store_true", help="use the original preamble of the file")
    parser.add_argument("--format", help="Specify the file format by its file ending")
    parser.add_argument(
        "--batch",
        metavar="FILE",
        help="Datei mit Liste von zu verarbeitenden Dateien"
    )

    args = parser.parse_args()

    stack = DocStack()

    stack.carnapedition = True

    script_path = os.path.dirname(os.path.abspath(__file__)) + "/carnap-fileopening.tex"
    with open(script_path, 'r', encoding='utf-8') as f:
            default_fileopening = f.read()
            f.close()

    if args.format and args.format != 'html': 
        file_format = "valeptex/" + args.format
        script_dir = os.path.dirname(os.path.abspath(__file__))
        subfolder_path = os.path.join(script_dir, file_format)
        if os.path.exists(subfolder_path) and os.path.isdir(subfolder_path):
            stack.output_format = args.format
            path = subfolder_path
            stack = load_jinja_specs(stack, path)
            if stack == None: sys.exit(1)
            # load the jinja template
            stack = load_jinja_template(stack, path)
            if stack == None: sys.exit(1)

            print(f"Identified format folder {file_format} and loaded jinja specs.")
        else:
            print(f"WARNING: subfolder '{file_format}' does not exist! HTML rendering is chosen instead ...")
            stack.output_format = 'html'

    if stack.output_format == 'html':
        script_dir = os.path.dirname(os.path.abspath(__file__))
        path = os.path.join(script_dir, 'valeptex/html')
        stack = load_jinja_specs(stack, path)
        if stack == None: sys.exit(1)
        # load the jinja template
        stack = load_jinja_template(stack, path)
        if stack == None: sys.exit(1)
        print('Rendering information for html has been loaded.')



    if args.normalize: stack.normalize = True
    if args.nologfile: stack.writelog = False
    if args.writeunknown: stack.writeunknown = True
    if args.useownpreamble: stack.defaultpreamble = False
    stack = load_preamble_string(stack, default_fileopening)
    stack.packages.clear()



    if args.tex_file:
        stack = valep_parse_latex_store_html(args.tex_file, stack)
        write_log(stack)

    elif args.folder:
        current_folder = os.getcwd()
        print("Converting .tex files in the current folder...")
        convert_folder_tex_to_html(current_folder, stack)
    elif args.subfolders:
        current_folder = os.getcwd()
        print("Converting .tex files in all subfolders...")
        convert_folder_tex_to_html(current_folder, stack, include_subfolders=True)
    elif args.entries:
        stack = convert_tex_to_diary_snippets()
    elif args.batch: 
        with open(args.batch, encoding="utf-8") as f:
            files = [line.strip() for line in f if line.strip()]

        for file in files:
            print("=" * 40)
            print(f"Verarbeite {file}")
            print("=" * 40)

            old_cwd = os.getcwd()
            file = os.path.abspath(file)

            try:
                os.chdir(os.path.dirname(file))

                stack = valep_parse_latex_store_html(
                    os.path.basename(file),
                    stack
                )

                write_log(stack)

            finally:
                os.chdir(old_cwd)
    
    else:
        print("Error: Please specify either a .tex file or --folder, --subfolders, or both.")

