from typing import List

from jinja2 import Environment, FileSystemLoader, TemplateError

from app.data_structures.processing import VideoProcessingResult
from app.data_structures.time_interval import DatetimeInterval
from app.exceptions import ReportGenerationError
from app.paths import COMMONS_DIR
from app.utils.format import format_datetime, format_time, format_timedelta


class ReportGenerator:
    """
    Class for generating HTML report from video processing results.
    """

    def __init__(
        self,
        results: List[VideoProcessingResult],
        processing_time_interval: DatetimeInterval,
        object_detection_enabled: bool,
    ) -> None:
        self.results = results
        self.processing_time_interval = processing_time_interval
        self.object_detection_enabled = object_detection_enabled

    def generate(self) -> str:
        """
        Generate HTML report from video processing results using Jinja2 template.
        :return:
        """
        env = Environment(loader=FileSystemLoader(searchpath=COMMONS_DIR / "templates"))
        try:
            template = env.get_template(
                "full_report.html",
                globals={
                    "format_timedelta": format_timedelta,
                    "format_datetime": format_datetime,
                    "format_time": format_time,
                },
            )
            text = template.render(
                start_time=self.processing_time_interval.start,
                end_time=self.processing_time_interval.end,
                video_results=self.results,
                object_detection_enabled=self.object_detection_enabled,
            )
        except TemplateError as ex:
            raise ReportGenerationError("Failed to generate report") from ex
        return text
