"""
Full-replay summary generator.

Rebuilds the summary from scratch by replaying all memories in chronological
order, chunk by chunk. This avoids carrying forward stale sections from prior
summaries while keeping the existing SummaryManager unchanged.
"""

from typing import Optional, List, Iterable

from .summary_generator import SummaryManager
from ..utils.timestamps import utc_now_iso


def _chunk(items: List[dict], chunk_size: int) -> Iterable[List[dict]]:
    if chunk_size <= 0:
        yield items
        return
    for i in range(0, len(items), chunk_size):
        yield items[i:i + chunk_size]


async def generate_replay_summary(
    manager: SummaryManager,
    trigger: str = "manual_full",
    model: str = "haiku",
    chunk_size: int = 50
) -> Optional[dict]:
    """
    Regenerate summary by replaying all memories from oldest to newest.

    Args:
        manager: SummaryManager instance
        trigger: Summary trigger label
        model: Claude model name
        chunk_size: Number of memories per summarization chunk

    Returns:
        New summary data dict or None if failed/skipped
    """
    if manager.store is None:
        print(f"[Summary:{manager.project}] No store available for replay")
        return None

    all_memories = manager.store.list_all(limit=10000, offset=0, sort_order="oldest")
    if not all_memories:
        print(f"[Summary:{manager.project}] No memories available for replay")
        return None

    current = manager.load_current()
    if current:
        current["pending"] = True
        manager.save_current(current)

    summary_text: Optional[str] = None
    for chunk in _chunk(all_memories, chunk_size):
        summary_text = await manager.generate_summary(
            previous_summary=summary_text,
            new_memories=chunk,
            model=model
        )
        if not summary_text:
            print(f"[Summary:{manager.project}] Replay generation failed (chunk)")
            return None

    if current:
        manager.add_to_history(current)

    latest_timestamp = all_memories[-1].get("created_at", "")
    new_version = (current.get("version", 0) if current else 0) + 1
    memory_count = manager.store.count()

    new_summary_data = {
        "project": manager.project,
        "version": new_version,
        "summary": summary_text or "",
        "generated_at": utc_now_iso(),
        "memory_count": memory_count,
        "last_memory_timestamp": latest_timestamp,
        "pending": False,
        "trigger": trigger,
        "new_memories_count": len(all_memories)
    }

    if manager.save_current(new_summary_data):
        print(f"[Summary:{manager.project}] Replay generated v{new_version} ({len(all_memories)} memories)")
        return new_summary_data

    return None
