#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Item 116: Memory consolidation priority queue (Consolidation — P28).

Modularized from stage_maintenance.py to keep it under 300 lines.

During consolidation, process items in priority order:
  1. High-salience first
  2. Then high-confidence
  3. Then most recent (timestamp)

This ensures the most important items get consolidated first if time runs out.
"""
import logging
from typing import Optional

log = logging.getLogger("pulse.daemons.consolidation.stage_priority_queue")


def build_consolidation_priority_queue(items: list) -> list:
    """Sort consolidation items in priority order.

    Priority key (descending):
      1. salience (higher = more salient)
      2. confidence (higher = more reliable)
      3. timestamp (newer = more recent)

    Args:
        items: List of dict-like brain items.

    Returns:
        New list sorted by descending priority.
    """
    try:
        def _priority_key(item: dict) -> tuple:
            sal = float(item.get("salience", 1.0) or 1.0)
            conf = float(item.get("confidence", 0.5) or 0.5)
            ts = item.get("timestamp") or item.get("updated_at") or ""
            return (sal, conf, ts)  # tuple sort: all descending via negation below

        sorted_items = sorted(
            items,
            key=lambda x: (
                -(float(x.get("salience", 1.0) or 1.0)),
                -(float(x.get("confidence", 0.5) or 0.5)),
                # Lexicographic timestamp sort — ISO 8601 strings sort correctly
                str(x.get("timestamp") or x.get("updated_at") or ""),
            ),
            reverse=False,  # negated values already handle descending for first two
        )
        return sorted_items
    except Exception as e:
        log.debug("build_consolidation_priority_queue failed: %s", e)
        return list(items)  # fail-open: return original order


def stage_consolidation_priority_queue(items: Optional[list] = None, verbose: bool = False) -> dict:
    """Stage wrapper: apply priority ordering to a list of consolidation candidates.

    If items is None, loads all valid lessons + failures + patterns from SQLite.

    Returns:
        dict with 'status', 'total', and 'ordered_items' keys.
    """
    try:
        if items is None:
            from pulse.core.brain_db import get_conn
            conn = get_conn()
            raw = []
            for table in ("lessons", "failures", "patterns"):
                try:
                    rows = conn.execute(
                        f"SELECT id, domain, salience, confidence, timestamp, validity "
                        f"FROM {table} WHERE validity = 'valid' LIMIT 2000"
                    ).fetchall()
                    for r in rows:
                        raw.append(dict(r) if hasattr(r, "keys") else {
                            "id": r[0], "domain": r[1],
                            "salience": r[2], "confidence": r[3],
                            "timestamp": r[4], "validity": r[5],
                            "_table": table,
                        })
                except Exception:
                    pass
            items = raw

        ordered = build_consolidation_priority_queue(items)
        if verbose:
            print(f"  [PRIORITY_QUEUE] {len(ordered)} items sorted for consolidation "
                  f"(top salience={ordered[0].get('salience', '?') if ordered else 'N/A'})")
        return {"status": "ok", "total": len(ordered), "ordered_items": ordered}
    except Exception as e:
        if verbose:
            print(f"  [PRIORITY_QUEUE] Error: {e}")
        return {"status": "error", "error": str(e), "total": 0, "ordered_items": []}
