#!/usr/bin/python3
#
# SPDX-License-Identifier: Apache-2.0
#

"""
This module provides functions to track and report key performance indicators (KPIs) for a program.
"""

import time
from utils.install_log import LOG

STAGES = []
METRICS = {}
START = 0


def init_kpi_metrics():
    """
    Initializes the global variable START with the current time to start tracking the
    duration of a program.
    """

    global START  # pylint: disable=global-statement
    START = time.time()


def get_formated_time(sec):
    """
    Takes the duration in seconds and formats it in hours, minutes and seconds.
    Returns the formatted string.
    """

    hours = sec // 3600
    sec %= 3600
    minutes = sec // 60
    sec %= 60
    seconds = sec
    if hours:
        return f"{hours:.0f}h {minutes:.0f}m {seconds:.2f}s"
    if minutes:
        return f"{minutes:.0f}m {seconds:.2f}s"
    return f"{seconds:.2f}s"


def set_kpi_metric(metric, duration):
    """Sets the duration of a metric and adds the metric to the global list of STAGES."""

    global METRICS, STAGES  # pylint: disable=global-statement, global-variable-not-assigned
    METRICS[metric] = duration
    STAGES.append(metric)


def print_kpi(metric):
    """Takes a metric as input and prints the duration of that metric using the LOG module."""

    if metric in STAGES:
        sec = METRICS[metric]
        LOG.info("  Time in stage '%s': %s ", metric, get_formated_time(sec))
    elif metric == 'total' and START:
        duration = time.time() - START
        LOG.info("  Total time: %s", get_formated_time(duration))


def get_kpi_str(metric):
    """Takes a metric as input and returns the duration of that metric as a formatted string."""

    msg = ""
    if metric in STAGES:
        sec = METRICS[metric]
        msg += f"  Time in stage '{metric}': {get_formated_time(sec)} \n"
    elif metric == 'total' and START:
        duration = time.time() - START
        msg += f"  Total time: {get_formated_time(duration)}\n"
    return msg


def get_kpi_metrics_str():
    """Returns a formatted string with all the metrics and their durations."""

    msg = "===================== Metrics ====================\n"
    for stage in STAGES:
        msg += get_kpi_str(stage)
    msg += get_kpi_str('total')
    msg += "===============================================\n"
    return msg


def print_kpi_metrics():
    """Prints all the metrics and their durations using the LOG module."""

    LOG.info("===================== Metrics ====================")
    for stage in STAGES:
        print_kpi(stage)
    print_kpi('total')
    LOG.info("==================================================")