from Dependency.Dependency import Dependency
from Metric.Code.AggregatedMetrics import AggregatedMetrics
from Metric.Code.FileMetrics import FileMetrics
from Metric.Code.SegmentedMetrics import SegmentedMetrics
from Metric.Git.GitMetrics import GitMetrics


class ProjectMetrics:
    def __init__(
        self,
        file_metrics: list[FileMetrics],
        git_metrics: GitMetrics | None,
        dependencies: list[Dependency] | None,
    ):
        self.file_metrics = file_metrics
        self.git_metrics = git_metrics
        self.dependencies = dependencies
        self.total_code_metrics = self._compile_total_metrics(self.file_metrics)

    def _compile_total_metrics(
        self, file_metrics: list[FileMetrics]
    ) -> AggregatedMetrics:
        files = 0
        locs = []
        avgCcPerFunctions = []
        maintainabilityIndices = []
        avgLocPerFunctions = []
        for file_metric in file_metrics:
            files += 1
            locs.append(file_metric.loc)
            avgCcPerFunctions.append(file_metric.avgCcPerFunction)
            maintainabilityIndices.append(file_metric.maintainabilityIndex)
            avgLocPerFunctions.append(file_metric.avgLocPerFunction)

        if files == 0:
            return AggregatedMetrics()

        return AggregatedMetrics(
            loc=sum(locs),
            avgCcPerFunction=self._avg(avgCcPerFunctions),
            maintainabilityIndex=self._avg(maintainabilityIndices),
            avgLocPerFunction=self._avg(avgLocPerFunctions),
            num_files=files,
            segmented_loc=SegmentedMetrics().set_loc(locs),
            segmented_complexity=SegmentedMetrics().set_complexity(avgCcPerFunctions),
            segmented_maintainability=SegmentedMetrics().set_maintainability(
                maintainabilityIndices
            ),
            segmented_method_size=SegmentedMetrics().set_method_size(
                avgLocPerFunctions
            ),
        )

    def _avg(self, items: list[float | int]) -> float:
        return sum(items) / len(items)
