"""Pattern: rank memories by recency, importance and relevance.

This follows the retrieval idea popularized by the Generative Agents paper
(Park et al., 2023): score = a*recency + b*importance + c*relevance, each
normalized to 0..1. Recency decays exponentially with time since last access.
"""
from __future__ import annotations

import math


def recency_weight(last_accessed: float, now: float, half_life_days: float = 30.0) -> float:
    """1.0 for 'just now', 0.5 after one half-life, approaching 0 for old items."""
    if half_life_days <= 0:
        raise ValueError("half_life_days must be positive")
    age_days = max(0.0, (now - last_accessed) / 86400.0)
    return math.pow(0.5, age_days / half_life_days)


def combined_score(*, relevance: float, last_accessed: float, importance: float, now: float,
                   half_life_days: float = 30.0, weights: tuple[float, float, float] = (1.0, 1.0, 1.0)) -> float:
    """Weighted average of relevance, recency and importance, in 0..1."""
    w_rel, w_rec, w_imp = weights
    total = w_rel + w_rec + w_imp
    if total <= 0:
        raise ValueError("weights must sum to a positive number")
    rec = recency_weight(last_accessed, now, half_life_days)
    return (w_rel * relevance + w_rec * rec + w_imp * importance) / total
