import jinja2
from pathlib import Path
import pandas as pd
from typing import Dict

from .util import label_fields


def write_report(output:Path, component_files:Dict, ocr_df:pd.DataFrame):
    """
    Writes an HTML report of the detection found.

    Args:
        output (Path): The path to write the output HTML.
        component_files (Dict): A dictionary with all the files generated by running the sheet component model.
        ocr_df (pd.DataFrame): The character recognition data for the institutional labels.
    """
    template_dir = Path(__file__).parent/"templates"
    loader = jinja2.FileSystemLoader(template_dir)

    def relative_to_output(path):
        try:
            return Path(path).relative_to(output.parent)
        except Exception:
            return path

    def get_classification(path):
        return Path(path).name.split(".")[-2].replace("_", " ").title()

    def truncate(string):
        if len(string) < 30:
            return string
        return f"{string[:30]}..."

    env = jinja2.Environment(
        loader=loader,
        autoescape=jinja2.select_autoescape()
    )
    env.globals['relative_to_output'] = relative_to_output
    env.globals['get_classification'] = get_classification
    env.globals['len'] = len
    env.globals['truncate'] = truncate
    template = env.get_template("report-template.html")

    result = template.render(
        component_files=component_files,
        label_fields=label_fields,
        ocr_df=ocr_df,
    )
    with open(str(output), 'w') as f:
        print(f"Writing result to {output}")
        f.write(result)                

