import sys
import os
import re
import subprocess
import argparse
import glob
import htmlcarnap





def convert_tex_to_html(tex_file, error=""):
    print(f"Converting {tex_file} to HTML...")

    # Custom File Opening
    fileopening = r'''\documentclass{carnap-compact}
\usepackage{valep-macros}
\usepackage{html}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage[T1]{fontenc}
\usepackage{geometry}
\usepackage{fancyhdr}
%\usepackage{graphicx}
\usepackage[colorlinks,bookmarksopen]{hyperref}
\usepackage{textcomp}
\usepackage{ifthen} 
\usepackage{tikz}
    
\newcommand{\editorpart}[1]{#1} 
\newcommand{\lita}[1]{\item#1}
\newcommand{\lith}[1]{\item#1}
\newcommand{\lititem}{\item }
\newcommand{\fnEE}[1]{\fnE{#1}}
\newcommand{\replsp}[2]{\soutsp{#1} \\textsp{#2}}
\newcommand{\nichtdrucken}[1]{}

'''

    # Construct the temporary tex file name
    temp_tex_file = tex_file.replace('.tex', '_temp.tex')

    # Read the LaTeX file
    with open(tex_file, 'r', encoding='utf-8') as f:
        tex_content = f.read()

    # Find the index of \begin{document}
    begin_document_index = tex_content.find(r'\begin{document}')

    # Make sure \begin{document} is found
    if begin_document_index != -1:
        # Split the content before and after \begin{document}
        preamble = tex_content[:begin_document_index]
        document_content = tex_content[begin_document_index:]

        # Write modified content to the temporary file
        with open(temp_tex_file, 'w', encoding='utf-8', newline='') as f:
            # Write the custom LaTeX code
            f.write(preamble)
            f.write(fileopening)
            # Write the document content
            f.write(document_content)
    else:
        # If \begin{document} is not found, write custom LaTeX code to the temporary file
        with open(temp_tex_file, 'w', encoding='utf-8', newline='') as f:
            # Write the custom LaTeX code
            f.write(fileopening)
            # Write the entire content of the TeX file
            f.write(tex_content)

    # removes the esoteric tex macro \kernDIMENSION and other silly stuff
    tex_content = htmlcarnap.remove_kern_etc(tex_content)

    # Check if \begin{document} and \end{document} are present
    if r'\begin{document}' in tex_content and r'\end{document}' in tex_content:
        # Replace the entire content before \begin{document} with custom code
        tex_content = fileopening + htmlcarnap.slicer(tex_content, r'\begin{document}')
    else:
        # Add custom code and \begin{document} at the beginning
        tex_content = fileopening + '\n\\begin{document}' + tex_content

        # Add \end{document} at the end
        tex_content += '\n\\end{document}'

    # Write modified content to a temporary file
    temp_tex_file = tex_file.replace('.tex', '_temp.tex')
    with open(temp_tex_file, 'w', encoding='utf-8') as f:
        f.write(tex_content)

    # Construct filename argument for plastex command
    base_filename = os.path.splitext(tex_file)[0]
    temp_html_filename = f"{base_filename}_temp.html"

    # Call plastex script
    plastex_command = [
        'plastex',
        temp_tex_file,
        '--split-level=-2',
        f'--filename={temp_html_filename}',
        f'--dir={os.getcwd()}',
        '--no-theme-css',
        '--no-theme-js',
        '--disable-images',
        '--no-load-tex-packages',
        '--tex-packages=valep-macros',
        '--packages-dir=D:\\Git_Server-LaTeX-VALEP\\py\\packages',
        '--no-theme-extras',
        '--extra-templates=D:\\Git_Server-LaTeX-VALEP\\py\\templates'
    ]
    
    process = subprocess.run(plastex_command)

    # Check if the process returned an error
    if process.returncode != 0:
        print(f"Error: plastex command failed with return code {process.returncode}")

    # Check if the temporary HTML file exists
    if not os.path.isfile(temp_html_filename):
        print(f"Error: Temporary HTML file '{temp_html_filename}' not found.")
        return

    # Perform string manipulation on the HTML file content
    with open(temp_html_filename, 'r', encoding='utf-8') as f:
        html_content = f.read()

    # Replace occurrences of <p><time with <p class="diary"><time
    html_content = html_content.replace('<p><time', '\n<p class="diary"><time')

    # replace latex character acronyms like "a "s and the like
    html_content = htmlcarnap.replace_latex_chars(html_content)
    html_content = htmlcarnap.replace_accented_chars(html_content)

    # merge note-x-mark and note-x-label tags to note-x tags  
    while not (html_content.find('note-e-mark') == -1 and html_content.find('note-a-mark') == -1):
        html_content = htmlcarnap.merge_mark_and_text(html_content, 'note-e')
        html_content = htmlcarnap.merge_mark_and_text(html_content, 'note-a')

    # add counters and labels to notes, indices, and readinglists
    html_content = htmlcarnap.add_all_to_notes_chapterwise(html_content)
    html_content = htmlcarnap.replace_tag_index(html_content, 'in-dex class="person"', '')
    html_content = htmlcarnap.replace_tag_index(html_content, 'in-dex class="institution"', '')
    html_content = htmlcarnap.replace_tag_index(html_content, 'in-dex class="location"', '')
    # needs to be extended with: concepts, other doc categories ...
    html_content = htmlcarnap.replace_tag_index(html_content, 'in-dex class="doc"', 'B')
    html_content = htmlcarnap.replace_tag_index(html_content, 'fac-simile', '')
    html_content = htmlcarnap.replace_tag_index(html_content, 'loc-ation', 'O')
    html_content = htmlcarnap.add_all_to_reading_lists(html_content)

    # resolve references to diary entries
    html_content = htmlcarnap.resolve_diary_references(html_content)

    # add content to diary entry time tags and add monthly label in left margin
    html_content = htmlcarnap.fill_time_tags(html_content)
    
    # add title to headline and task bar and produce the table of content
    html_content = htmlcarnap.make_title_toc(html_content)

    # Replace occurrences of </time> followed by whitespace,
    # then </p> followed by whitespace, then <p> with </time>
    html_content = re.sub(r'</time>\s+</p>\s+<p>', '</time>', html_content)

    # Write the modified HTML content to the final HTML file
    final_html_filename = f"{base_filename}.html"
    with open(final_html_filename, 'w', encoding='utf-8', newline='') as f:
        f.write(html_content)

    # Delete temporary tex and HTML files
    os.remove(temp_tex_file)
    os.remove(temp_html_filename)

    return error


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}')
    with open('D:/Git_Server-LaTeX-VALEP/py/templates/Themes/default/default-layout.jinja2', 'r', encoding='utf-8', newline='') as template:
        html_template = template.read()
    html_template = re.sub('<div class="table-of-content">','<div class="table-of-content" style="display:none">',html_template)
    html_template = re.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 = re.search('<h1.*?</h1>',html_content)[0]
            html_template_header = html_template_header[0:len(html_template_header)-5]
            html_template_begin = re.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 = re.search(r'datetime="(.*?)"',snippet)
                if date:
                    nicedate = htmlcarnap.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.')

def add_file_names_to_tex_files():
    print("Not yet implemented.")


def convert_folder_tex_to_html(folder_path, 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',
                    '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 or tex_file.find('_temp.tex') > -1 or tex_file.find('_internal.tex') > -1):
            try:
                error = convert_tex_to_html(tex_file,error)
            except: 
                print(f"ERROR: conversion of file {tex_file} failed.")
                error = error + f"ERROR: conversion of file {tex_file} failed."

    with open('plastex.log', 'w', encoding='utf-8', newline='') as f:
        f.write(error)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Convert LaTeX files to HTML")
    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("--addfilenames", action="store_true", help="Add all filenames on top of .tex files")

    
    args = parser.parse_args()

    if args.tex_file:
        error = convert_tex_to_html(args.tex_file)
    elif args.folder:
        current_folder = os.getcwd()
        print("Converting .tex files in the current folder...")
        convert_folder_tex_to_html(current_folder)
    elif args.subfolders:
        current_folder = os.getcwd()
        print("Converting .tex files in all subfolders...")
        convert_folder_tex_to_html(current_folder, include_subfolders=True)
    elif args.entries:
        error = convert_tex_to_diary_snippets()
    elif args.addfilenames:
        add_file_names_to_tex_files()
    else:
        print("Error: Please specify either a .tex file or --folder, --subfolders, or both.")


        