#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Phase 2A: Multi-Timescale Consolidation (Deep Consolidation)

Upgrades knowledge validity based on retrieval success over time,
or archives dead knowledge that has completely decayed.
"""
from datetime import datetime, timezone, timedelta
from pulse.core.brain_db import get_conn
from pulse.core import event_bus

def deep_consolidation_cycle() -> dict:
    """Runs a deep consolidation sweep over the brain database."""
    conn = get_conn()
    now = datetime.now(timezone.utc)
    fourteen_days_ago = (now - timedelta(days=14)).isoformat()
    thirty_days_ago = (now - timedelta(days=30)).isoformat()

    stats = {"permanent": 0, "archived": 0}
    tables = ["lessons", "failures", "patterns", "decisions", "facts"]

    with conn:
        for table in tables:
            # 1. Promote to 'permanent'
            # Items with confidence >= 0.7, retrieval_count >= 5, age >= 14 days
            res = conn.execute(f"""
                UPDATE {table}
                SET validity = 'permanent'
                WHERE validity = 'valid'
                  AND confidence >= 0.7
                  AND access_count >= 5
                  AND timestamp <= ?
            """, (fourteen_days_ago,))
            stats["permanent"] += res.rowcount

            # 2. Demote to 'archived'
            # Items unretrieved 30 days (last_accessed or timestamp) with confidence < 0.3
            res = conn.execute(f"""
                UPDATE {table}
                SET validity = 'archived'
                WHERE validity = 'valid'
                  AND confidence < 0.3
                  AND coalesce(last_accessed, timestamp) <= ?
            """, (thirty_days_ago,))
            stats["archived"] += res.rowcount

    event_bus.publish("consolidation.deep.complete", "deep_consolidation", stats)
    return stats
