import re
import sys

def default_options():
    return {
        "<columns": 4,
        "<corners": "2mm",
        "<colorcell": "orange!20",
        "<tabularwidth": "\\textwidth",
        "<cellheight": "2em",
        "<tabulartitlecolor": "orange!30!black",
        "<texttitlecolor": "yellow",
        "<firstcolumncolor": None,
        "<lastcolumncolor": None,
        "<tabularheadcolor": "orange!50!black",
        "<textheadcolor": "white",
        "<textfootcolor": "white",
        "<tabularfootcolor": "orange!75!black",
        "<textcolor": "black",
        "<marginh": "1mm", # marge horizontale entre deux colonnes
        "<marginv": "2mm", # marge verticale entre deux lignes
        "<marginvtitle": "1mm" # marge verticale entre le titre et la ligne suivante
    }


def generate_tikztabular(num, basedir):
    options = default_options() # on charge les options par défaut
    
    nameaux = f'{basedir}tikztabular-{num}.aux'
    
    with open(nameaux, 'r') as file:
        content = file.read()

    numcols = re.search(r'<columns\s*=\s*(\d+)', content).group(1)
    
    match = re.search(r'<colorcell\s*=\s*([^\n]+)', content)
    colorcell = match.group(1) if match else options['<colorcell']
    
    match = re.search(r'<corners\s*=\s*([^\n]+)', content)
    corners = match.group(1) if match else options['<corners']
    
    match = re.search(r'<cellheight\s*=\s*([^\n]+)', content)
    cellheight = match.group(1) if match else options['<cellheight']
    
    match = re.search(r'<textcolor\s*=\s*([^\n]+)', content)
    textcolor = match.group(1) if match else options['<textcolor']
    
    match = re.search(r'<texttitlecolor\s*=\s*([^\n]+)', content)
    texttitlecolor = match.group(1) if match else options['<texttitlecolor']
    
    match = re.search(r'<tabulartitlecolor\s*=\s*([^\n]+)', content)
    tabulartitlecolor = match.group(1) if match else options['<tabulartitlecolor']
    
    match = re.search(r'<textheadcolor\s*=\s*([^\n]+)', content)
    textheadcolor = match.group(1) if match else options['<textheadcolor']
    
    match = re.search(r'<textfootcolor\s*=\s*([^\n]+)', content)
    textfootcolor = match.group(1) if match else options['<textfootcolor']
    
    match = re.search(r'<firstcolumncolor\s*=\s*([^\n]+)', content)
    firstcolumncolor = match.group(1) if match else options['<firstcolumncolor']
    if firstcolumncolor is None:
        firstcolumncolor = colorcell

    match = re.search(r'<lastcolumncolor\s*=\s*([^\n]+)', content)
    lastcolumncolor = match.group(1) if match else options['<lastcolumncolor']
    if lastcolumncolor is None:
       lastcolumncolor = colorcell
    
    match = re.search(r'<tabularheadcolor\s*=\s*([^\n]+)', content)
    tabularheadcolor = match.group(1) if match else options['<tabularheadcolor']
    
    match = re.search(r'<tabularfootcolor\s*=\s*([^\n]+)', content)
    tabularfootcolor = match.group(1) if match else options['<tabularfootcolor']
    
    match = re.search(r'<marginv\s*=\s*([^\n]+)', content)
    marginv = match.group(1) if match else options['<marginv']
    
    match = re.search(r'<marginvtitle\s*=\s*([^\n]+)', content)
    marginvtitle = match.group(1) if match else options['<marginvtitle']
    
    match = re.search(r'<marginh\s*=\s*([^\n]+)', content)
    marginh = match.group(1) if match else options['<marginh']
    
    match = re.search(r'<tabularwidth\s*=\s*([^\n]+)', content)
    tabularwidth = match.group(1) if match else options['<tabularwidth']
    
    # Définition de la largeur des colonnes
    tikz_code = "\\pgfmathsetlength{\cellwidth}{("+tabularwidth+"-2*("+numcols+"-1)*"+marginh+")/"+numcols+"}\n"
    
    # Définition des styles de nodes
    tikz_code += "\\tikzset{cell/.style={inner xsep=0mm,outer ysep="+marginv+", outer xsep="+marginh+", minimum height="+cellheight+",align=center,rounded corners="+corners+",fill="+colorcell+",text="+textcolor+",minimum width=\\cellwidth}}\n"
    tikz_code += "\\tikzset{titlehead/.style={inner xsep=0mm,outer ysep="+marginvtitle+", outer xsep="+marginh+", minimum height="+cellheight+", align=center,rounded corners="+corners+",fill="+tabulartitlecolor+",text="+texttitlecolor+",minimum width="+tabularwidth+"}}\n"
    tikz_code += "\\tikzset{head/.style={inner xsep=0mm,outer ysep="+marginv+", outer xsep="+marginh+", minimum height="+cellheight+", align=center,rounded corners="+corners+",fill="+tabularheadcolor+",text="+textheadcolor+",minimum width=\\cellwidth}}\n"
    tikz_code += "\\tikzset{foot/.style={inner xsep=0mm,outer ysep="+marginv+", outer xsep="+marginh+", minimum height="+cellheight+", align=center,rounded corners="+corners+",fill="+tabularfootcolor+",text="+textfootcolor+",minimum width=\\cellwidth}}\n"
    tikz_code += "\\tikzset{firstcolumn/.style={inner xsep=0mm,outer ysep="+marginv+", outer xsep="+marginh+", fill="+firstcolumncolor+"}}\n"
    tikz_code += "\\tikzset{lastcolumn/.style={inner xsep=0mm,outer ysep="+marginv+", outer xsep="+marginh+", fill="+lastcolumncolor+"}}\n"
    
    
    # Supprimer les lignes contenant ces mots-clés
    tabular = [
        line for line in content.splitlines()
        if not any(keyword in line for keyword in options.keys())
        and line !=''
    ]

    # À ce stade, tabular est une liste qui contient les données de tableau uniquement
    
    

    # On commence à générer le code LaTeX
    tikz_code += "\\begin{scope}\n"
    
    line_count = 0
    head = False
    foot = False
    title = False
    
    for line in tabular:        
        if "[tabularhead]" in line:
            head = True
        if "[endtabularhead]" in line:
            head = False
        if "[tabularfoot]" in line:
            foot = True
        if "[tabulartitle]" in line:
            title = True
        if "[endtabulartitle]" in line:
            title = False
        
        if head == True:
            style_cell = "head"
        elif foot == True:
            style_cell = "foot"
        elif title == True:
            style_cell = "titlehead"
        else:
            style_cell = "cell"
            
        column_count = 0        
        
        if not any(keyword in line for keyword in ("[tabularhead]", "[endtabularhead]", "[tabularfoot]", "[tabulartitle]" , "[endtabulartitle]")):
            line_count += 1
            for cell_text in line.split('&'):
                column_count += 1
                
                if column_count == 1 and line_count == 1:
                    if title == False:
                        tikz_code += f"\\node[{style_cell},firstcolumn] (cell-1-1) {{{cell_text}}};\n"
                    else:
                        tikz_code += f"\\node[{style_cell}] (cell-1-1) {{ {cell_text} }};\n"
                elif column_count != 1 and line_count == 1:
                    if column_count == int(numcols):
                        tikz_code += f"\\node[{style_cell},lastcolumn,anchor=west] (cell-1-{column_count}) at (cell-1-{column_count-1}.east) {{ \\begin{{minipage}}{{ \\dimexpr\\cellwidth-4mm }}\\centering {cell_text} \\end{{minipage}} }};\n"
                    else:
                        tikz_code += f"\\node[{style_cell},anchor=west] (cell-1-{column_count}) at (cell-1-{column_count-1}.east) {{ \\begin{{minipage}}{{ \\dimexpr\\cellwidth-4mm }}\\centering {cell_text} \\end{{minipage}} }};\n"
                else:
                    if column_count == 1 and (head == False) and (title == False) and (foot == False):
                        stylecomp = "firstcolumn"
                    elif column_count == int(numcols) and (head == False) and (title == False) and (foot == False):
                        stylecomp = "lastcolumn"
                    else:
                        stylecomp = ""
                    
                    if column_count == 1:
                        tikz_code += f"\\node[{style_cell},{stylecomp},anchor=north west] (cell-{line_count}-{column_count}) at (cell-{line_count-1}-1.south west) {{ \\begin{{minipage}}{{ \\dimexpr\\cellwidth-4mm }}\\centering {cell_text} \\end{{minipage}} }};\n"            
                    else:
                        tikz_code += f"\\node[{style_cell},{stylecomp},anchor=west] (cell-{line_count}-{column_count}) at (cell-{line_count}-{column_count-1}.east) {{ \\begin{{minipage}}{{ \\dimexpr\\cellwidth-4mm }}\\centering {cell_text} \\end{{minipage}} }};\n"

    tikz_code += "\\end{scope}"
    
    nametabular = f'{basedir}tikztabular-{num}.tex'

    with open(nametabular, 'w') as file:
        file.write(tikz_code)

def extract_number_and_path(argument):
    # Diviser l'argument en parties en utilisant 'dir-' comme séparateur
    parts = argument.split('-dir-')

    if len(parts) != 2:
        raise ValueError("Format d'argument inattendu")

    # Extraire le numéro
    num_part = parts[0]
    number = num_part.replace('num-', '')

    # Le chemin est la deuxième partie
    path = parts[1]

    return number, path

if __name__ == "__main__":
    argument = sys.argv[1]
    
    try:
        number, path = extract_number_and_path(argument)
        print(number, path)
        generate_tikztabular(number, path)
        
    except ValueError as e:
        print(e)
    
    
