"""Statistics tracking for remediation operations."""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime  # noqa: TC003 - needed at runtime for dataclass fields


@dataclass
class RemediationStats:
    """Statistics about remediation operations."""

    # Detection stats
    total_checks: int = 0
    checks_passed: int = 0
    checks_failed: int = 0

    # Remediation stats
    total_remediations: int = 0
    remediations_successful: int = 0
    remediations_failed: int = 0
    remediations_skipped_dry_run: int = 0
    remediations_skipped_cooldown: int = 0
    remediations_skipped_rate_limit: int = 0

    # Verification stats
    verifications_total: int = 0
    verifications_passed: int = 0
    verifications_failed: int = 0

    # Bundle sync stats
    bundle_syncs: int = 0
    bundle_sync_failures: int = 0
    signature_validations: int = 0
    signature_failures: int = 0

    # Timing
    last_check_time: datetime | None = None
    last_remediation_time: datetime | None = None
    last_bundle_sync_time: datetime | None = None
    average_check_duration_ms: float = 0.0
    average_remediation_duration_ms: float = 0.0

    # Rate limiting tracking
    remediations_this_hour: int = 0
    hour_start_time: datetime | None = None

    # Active rule/playbook counts
    active_rules: int = 0
    active_playbooks: int = 0

    def record_check(self, passed: bool, duration_ms: float) -> None:
        """Record a detection check result."""
        self.total_checks += 1
        if passed:
            self.checks_passed += 1
        else:
            self.checks_failed += 1

        # Update running average
        n = self.total_checks
        self.average_check_duration_ms = (
            self.average_check_duration_ms * (n - 1) + duration_ms
        ) / n

    def record_remediation(
        self,
        success: bool,
        duration_ms: float,
        *,
        dry_run: bool = False,
        skipped_cooldown: bool = False,
        skipped_rate_limit: bool = False,
    ) -> None:
        """Record a remediation attempt result."""
        if dry_run:
            self.remediations_skipped_dry_run += 1
            return

        if skipped_cooldown:
            self.remediations_skipped_cooldown += 1
            return

        if skipped_rate_limit:
            self.remediations_skipped_rate_limit += 1
            return

        self.total_remediations += 1
        self.remediations_this_hour += 1

        if success:
            self.remediations_successful += 1
        else:
            self.remediations_failed += 1

        # Update running average
        n = self.total_remediations
        self.average_remediation_duration_ms = (
            self.average_remediation_duration_ms * (n - 1) + duration_ms
        ) / n

    def record_verification(self, passed: bool) -> None:
        """Record a verification result."""
        self.verifications_total += 1
        if passed:
            self.verifications_passed += 1
        else:
            self.verifications_failed += 1

    def record_bundle_sync(self, success: bool) -> None:
        """Record a bundle sync attempt."""
        self.bundle_syncs += 1
        if not success:
            self.bundle_sync_failures += 1

    def record_signature_validation(self, valid: bool) -> None:
        """Record a signature validation result."""
        self.signature_validations += 1
        if not valid:
            self.signature_failures += 1

    def reset_hourly_counter(self, hour_start: datetime) -> None:
        """Reset the hourly remediation counter."""
        self.remediations_this_hour = 0
        self.hour_start_time = hour_start

    def to_dict(self) -> dict[str, object]:
        """Convert stats to dictionary for reporting."""
        return {
            "checks": {
                "total": self.total_checks,
                "passed": self.checks_passed,
                "failed": self.checks_failed,
                "average_duration_ms": self.average_check_duration_ms,
            },
            "remediations": {
                "total": self.total_remediations,
                "successful": self.remediations_successful,
                "failed": self.remediations_failed,
                "skipped_dry_run": self.remediations_skipped_dry_run,
                "skipped_cooldown": self.remediations_skipped_cooldown,
                "skipped_rate_limit": self.remediations_skipped_rate_limit,
                "average_duration_ms": self.average_remediation_duration_ms,
                "this_hour": self.remediations_this_hour,
            },
            "verifications": {
                "total": self.verifications_total,
                "passed": self.verifications_passed,
                "failed": self.verifications_failed,
            },
            "bundle": {
                "syncs": self.bundle_syncs,
                "sync_failures": self.bundle_sync_failures,
                "signature_validations": self.signature_validations,
                "signature_failures": self.signature_failures,
                "last_sync": (
                    self.last_bundle_sync_time.isoformat()
                    if self.last_bundle_sync_time
                    else None
                ),
            },
            "active": {
                "rules": self.active_rules,
                "playbooks": self.active_playbooks,
            },
            "last_check": (
                self.last_check_time.isoformat() if self.last_check_time else None
            ),
            "last_remediation": (
                self.last_remediation_time.isoformat()
                if self.last_remediation_time
                else None
            ),
        }
