"""Memory importance auto-calibration from access patterns."""

from __future__ import annotations

import math
from collections import defaultdict


class ImportanceCalibrator:
    """Learn optimal importance from access patterns per source."""

    LEARNING_RATE = 0.1
    MIN_SAMPLES = 10

    def __init__(self):
        self._source_accesses: dict[str, int] = defaultdict(int)
        self._total_accesses = 0
        self._source_avg_importance: dict[str, float] = {}

    def record_access(self, source: str, importance: float) -> None:
        """Record a memory access event for calibration."""
        self._source_accesses[source] += 1
        self._total_accesses += 1

        prev = self._source_avg_importance.get(source, importance)
        alpha = 2.0 / (self._source_accesses[source] + 1)
        self._source_avg_importance[source] = prev * (1 - alpha) + importance * alpha

    def calibrate(self, source: str, base_importance: float) -> float:
        """Adjust importance based on learned source access patterns."""
        if self._total_accesses < self.MIN_SAMPLES:
            return base_importance

        count = self._source_accesses.get(source, 0)
        if count == 0:
            return max(0.01, min(1.0, base_importance * 0.9))

        unique_sources = max(len(self._source_accesses), 1)
        expected_rate = 1.0 / unique_sources
        actual_rate = count / self._total_accesses

        ratio = actual_rate / expected_rate if expected_rate > 0 else 1.0
        adjustment = self.LEARNING_RATE * math.log2(max(ratio, 0.1))

        avg_imp = self._source_avg_importance.get(source, 0.5)
        bias = (avg_imp - 0.5) * 0.1

        calibrated = base_importance + adjustment + bias
        return max(0.01, min(1.0, calibrated))
