"""Prints a LaTeX representation of the infrastructure."""

import pandas as pd

from scans2any.internal import Infrastructure, printer
from scans2any.writers.dataframe_creator import create_dataframes

NAME = "latex"
PROPERTIES = {
    "binary": False,
    "ignore-conflicts": False,
}


def write(infra: Infrastructure, args) -> str:
    """
    Convert the internal representation of the infrastructure
    into LaTeX format using pandas to_latex.

    Parameters
    ----------
    infra : Infrastructure
        The infrastructure to convert
    columns : tuple[str, ...]
        The columns to include in the output
    multi_table : bool, optional
        Whether to create one table for all hosts, by default False\

    Returns
    -------
    str
        The LaTeX representation of the infrastructure
    """
    infra.sort()
    infra.cleanup_names('{}\\_$%"')

    # Create DataFrames
    merge_symbol = " \\\\ "  # LaTeX line break
    dfs = create_dataframes(
        infra,
        columns=args.columns,
        multi_table=args.multi_table,
        merge_symbol=merge_symbol,
    )

    latex_tables = []
    for df in dfs:
        # This makes cells with multiple entries behave like inner tables,
        # the [t] makes the entries align with entries in other cells
        df.columns = pd.Index(
            [
                f"\\makecell[l]{{{col.replace('\n', ' \\\\ ')}}}"
                if isinstance(col, str)
                else col
                for col in df.columns
            ]
        )
        df = df.map(
            lambda x: f"\\makecell[l]{{{x.replace('\n', ' \\\\ ')}}}"
            if isinstance(x, str)
            else x
        )
        latex_table = df.to_latex(
            index=False,
            escape=False,
            longtable=True,
            caption="Infrastructure Scan Results"
            if not args.multi_table
            else "Host Information",
        )
        latex_tables.append(latex_table)

    # Document preamble
    preamble = r"""\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{longtable}
\usepackage{booktabs}
\usepackage{geometry}
\geometry{a4paper, margin=2pt, landscape}
\usepackage{makecell}
\usepackage{array}
\usepackage{multirow}
\title{Infrastructure Scan Results}
\author{Generated by scans2any}
\date{\today}

\begin{document}
\maketitle

"""

    # Document closing
    closing = r"""
\end{document}
"""

    # Join tables with page breaks
    content = "\n\n".join(latex_tables)

    # Full LaTeX document
    full_doc = preamble + content + closing

    printer.success(
        f"LaTeX output with {len(dfs)} tables has been created from parsed input data"
    )

    return full_doc
