"""Result aggregation for Tru-Guard."""

from typing import Any

from trusys.types import (
    ActionRecord,
    AggregatedResult,
    ScanResult,
    ScanType,
    Severity,
    Violation,
)


class ResultAggregator:
    """Aggregates and analyzes scan results."""

    def __init__(self) -> None:
        """Initialize the aggregator."""
        self._results: list[ScanResult] = []
        self._actions: list[ActionRecord] = []

    def add_result(self, result: ScanResult) -> None:
        """Add a scan result.

        Args:
            result: Scan result to add
        """
        self._results.append(result)

    def add_action(self, action: ActionRecord) -> None:
        """Add an action record.

        Args:
            action: Action record to add
        """
        self._actions.append(action)

    def aggregate(
        self,
        final_content: str | None = None,
        total_time_ms: float = 0.0,
    ) -> AggregatedResult:
        """Aggregate all results into a single result.

        Args:
            final_content: Final content after all actions
            total_time_ms: Total execution time

        Returns:
            Aggregated result
        """
        passed = all(r.passed for r in self._results)

        return AggregatedResult(
            passed=passed,
            results=self._results.copy(),
            final_content=final_content,
            actions_taken=self._actions.copy(),
            total_execution_time_ms=total_time_ms,
        )

    def get_violations_by_severity(self) -> dict[Severity, list[Violation]]:
        """Get all violations grouped by severity.

        Returns:
            Dictionary mapping severity to violations
        """
        by_severity: dict[Severity, list[Violation]] = {
            Severity.LOW: [],
            Severity.MEDIUM: [],
            Severity.HIGH: [],
            Severity.CRITICAL: [],
        }

        for result in self._results:
            for violation in result.violations:
                by_severity[violation.severity].append(violation)

        return by_severity

    def get_violations_by_scanner(self) -> dict[str, list[Violation]]:
        """Get all violations grouped by scanner.

        Returns:
            Dictionary mapping scanner name to violations
        """
        by_scanner: dict[str, list[Violation]] = {}

        for result in self._results:
            if result.scanner_name not in by_scanner:
                by_scanner[result.scanner_name] = []
            by_scanner[result.scanner_name].extend(result.violations)

        return by_scanner

    def get_summary(self) -> dict[str, Any]:
        """Get a summary of the aggregated results.

        Returns:
            Summary dictionary
        """
        total_violations = sum(len(r.violations) for r in self._results)
        failed_scanners = [r.scanner_name for r in self._results if not r.passed]

        return {
            "total_scanners": len(self._results),
            "passed_scanners": len(self._results) - len(failed_scanners),
            "failed_scanners": failed_scanners,
            "total_violations": total_violations,
            "total_actions": len(self._actions),
            "overall_passed": len(failed_scanners) == 0,
        }

    def clear(self) -> None:
        """Clear all results and actions."""
        self._results.clear()
        self._actions.clear()
