"""Tests for sleep-time compute — importance scoring, recency, normalization, results."""

from __future__ import annotations

from datetime import UTC, datetime, timedelta

from arandu.background.sleep_time import (
    EntityImportanceResult,
    SummaryRefreshResult,
    _normalize,
    _recency_score,
)

# ---------------------------------------------------------------------------
# _recency_score
# ---------------------------------------------------------------------------


def test_recency_score_none():
    """None last_seen → 0.0."""
    now = datetime.now(UTC)
    assert _recency_score(None, now) == 0.0


def test_recency_score_now():
    """Just seen → ~1.0."""
    now = datetime.now(UTC)
    score = _recency_score(now, now)
    assert score > 0.99


def test_recency_score_one_halflife():
    """After one halflife → ~0.5."""
    now = datetime.now(UTC)
    one_halflife_ago = now - timedelta(days=30)
    score = _recency_score(one_halflife_ago, now, halflife_days=30)
    assert abs(score - 0.5) < 0.01


def test_recency_score_naive_datetime():
    """Naive datetime should be treated as UTC."""
    now = datetime.now(UTC)
    naive = now.replace(tzinfo=None)
    score = _recency_score(naive, now, halflife_days=30)
    assert score > 0.99


def test_recency_score_custom_halflife():
    """Custom halflife should affect decay rate."""
    now = datetime.now(UTC)
    past = now - timedelta(days=7)
    score_short = _recency_score(past, now, halflife_days=7)
    score_long = _recency_score(past, now, halflife_days=90)
    assert score_long > score_short


# ---------------------------------------------------------------------------
# _normalize
# ---------------------------------------------------------------------------


def test_normalize_empty():
    """Empty list → empty list."""
    assert _normalize([]) == []


def test_normalize_single():
    """Single value → 0.5."""
    assert _normalize([42.0]) == [0.5]


def test_normalize_uniform():
    """All same values → all 0.5."""
    assert _normalize([3.0, 3.0, 3.0]) == [0.5, 0.5, 0.5]


def test_normalize_range():
    """Min → 0.0, max → 1.0."""
    result = _normalize([10.0, 20.0, 30.0])
    assert abs(result[0] - 0.0) < 0.001
    assert abs(result[1] - 0.5) < 0.001
    assert abs(result[2] - 1.0) < 0.001


# ---------------------------------------------------------------------------
# Result dataclasses
# ---------------------------------------------------------------------------


def test_entity_importance_result_defaults():
    """EntityImportanceResult should have sane defaults."""
    r = EntityImportanceResult()
    assert r.entities_scored == 0
    assert r.top_entities == []


def test_summary_refresh_result_defaults():
    """SummaryRefreshResult should have sane defaults."""
    r = SummaryRefreshResult()
    assert r.summaries_refreshed == 0
    assert r.summaries_skipped == 0
