"""
RULE 7 COMPLIANT: Uses Elestio PostgreSQL via genesis_db module.
"""
import json
import os
import logging
from datetime import datetime, timedelta
from pathlib import Path

# RULE 7: Use PostgreSQL via genesis_db (no sqlite3)
from core.genesis_db import connection

logger = logging.getLogger(__name__)


class MemoryDigestion:
    """
    Night-Cycle Memory Digestion (RULE 7: PostgreSQL):
    - Sorting: Moving working memory to episodic/semantic.
    - Cropping: Pruning low-score episodic memories.
    - Sorting: Categorizing by domain and impact.
    """
    def __init__(self):
        # RULE 7: Uses PostgreSQL via genesis_db (no sqlite3/db_path)
        pass

    def digest(self):
        print(f"🌙 [DIGESTION] Starting memory optimization cycle...")

        # 1. Prune Old Low-Impact Episodes
        self._prune_low_impact(threshold=0.4, age_days=7)

        # 2. Promote High-Frequency Memories
        # (This would normally interact with Redis, but here we focus on local state)

        # 3. Consolidate Semantic Entities
        self._consolidate_semantic()

        print(f"✅ [DIGESTION] Cycle complete.")

    def _prune_low_impact(self, threshold, age_days):
        """Prune low-impact memories (RULE 7: PostgreSQL)."""
        cutoff = (datetime.now() - timedelta(days=age_days)).isoformat()
        print(f"  - Pruning memories with score < {threshold} older than {age_days} days...")
        try:
            with connection() as conn:
                cursor = conn.cursor()
                cursor.execute(
                    "DELETE FROM episodic_memories WHERE score < %s AND timestamp < %s",
                    (threshold, cutoff)
                )
                print(f"    Deleted {cursor.rowcount} memories.")
        except Exception as e:
            logger.warning(f"Failed to prune memories: {e}")

    def _consolidate_semantic(self):
        # Log-based consolidation for MCP
        log_path = Path(r"e:\genesis-system\data\semantic_memory_log.json")
        if log_path.exists():
            print(f"  - Consolidating semantic logs for MCP sync...")
            # Logic to deduplicate pending entities
            pass

if __name__ == "__main__":
    digestor = MemoryDigestion()
    digestor.digest()
