"""Temporal decay and review scheduling utilities."""

from __future__ import annotations

import math

REVIEW_INTERVALS_DAYS = [1, 3, 7, 14, 30, 60, 120]


def ebbinghaus_retention(
    original_importance: float,
    hours_since_last_access: float,
    reinforcement_count: int,
    stability_factor: float = 1.0,
) -> float:
    """Compute decayed importance using a simplified Ebbinghaus curve."""
    stability = stability_factor * (1 + original_importance * 2)
    reinforcement = max(1, reinforcement_count)
    effective_stability = stability * math.log2(reinforcement + 1)

    if effective_stability <= 0:
        return 0.01

    retention = math.exp(-hours_since_last_access / (effective_stability * 24))
    return max(original_importance * retention, 0.01)


def temporal_weight(memory_created_at_ms: int, current_time_ms: int) -> float:
    """Compute temporal relevance weight used during retrieval."""
    hours_ago = (current_time_ms - memory_created_at_ms) / (1000 * 3600)

    if hours_ago < 1:
        return 1.0
    if hours_ago < 24:
        return 0.8
    if hours_ago < 168:
        return 0.6
    if hours_ago < 720:
        return 0.4
    return 0.2


def next_review_time_ms(access_count: int, last_accessed_ms: int) -> int:
    """Compute spaced repetition review schedule timestamp."""
    interval_idx = min(max(0, access_count), len(REVIEW_INTERVALS_DAYS) - 1)
    days = REVIEW_INTERVALS_DAYS[interval_idx]
    return int(last_accessed_ms + (days * 86400 * 1000))
