#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Item 127: Sleep pressure accumulation (Consolidation -- P30).

Models adenosine accumulation in the brain: the longer/more items accumulate
without consolidation, the higher the "sleep pressure". Higher pressure drives
more aggressive (larger-batch) consolidation during the next sleep cycle.

Extracted from sleep_cycle.py to keep that file under 300 lines.
"""
import logging
from pathlib import Path

log = logging.getLogger("pulse.synthesis.sleep_pressure")

_MIN_BATCH_SIZE = 5
_MAX_BATCH_SIZE = 50


def _get_sleep_pressure(brain_files: dict) -> int:
    """Count total unprocessed items across JSONL brain files.

    Args:
        brain_files: Dict mapping section name to Path (from sleep_cycle.BRAIN_FILES)

    Returns:
        Total item count (proxy for consolidation backlog / sleep pressure).
    """
    try:
        from pulse.core.brain_utils import read_jsonl_entries
        total = 0
        for fp in brain_files.values():
            if isinstance(fp, Path) and fp.exists():
                rows = read_jsonl_entries(fp)
                total += len(rows)
        return total
    except Exception as e:
        log.debug("_get_sleep_pressure failed: %s", e)
        return 0  # fail-open


def get_adaptive_batch_size(brain_files: dict) -> int:
    """Return consolidation batch size scaled by sleep pressure.

    Low pressure (<=50 items)  -> small batches (_MIN_BATCH_SIZE=5).
    High pressure (>=500 items) -> large batches (_MAX_BATCH_SIZE=50).
    Linear interpolation between the two extremes.

    Args:
        brain_files: Dict mapping section name to Path (from sleep_cycle.BRAIN_FILES)
    """
    try:
        pressure = _get_sleep_pressure(brain_files)
        if pressure <= 50:
            return _MIN_BATCH_SIZE
        if pressure >= 500:
            return _MAX_BATCH_SIZE
        ratio = (pressure - 50) / (500 - 50)
        return round(_MIN_BATCH_SIZE + ratio * (_MAX_BATCH_SIZE - _MIN_BATCH_SIZE))
    except Exception as e:
        log.debug("get_adaptive_batch_size failed: %s", e)
        return 10  # fail-open default
