#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Memory integration index — Item 170.

  - Item 170: Memory integration index (Monitoring)

Ratio of items connected via graph edges vs isolated items.
High integration = well-organized brain.
"""
import logging
from typing import Dict, Any

log = logging.getLogger("pulse.brain.memory_integration_index")


def get_integration_index() -> Dict[str, Any]:
    """Compute the ratio of brain items connected via graph edges.

    Returns:
        {
            total_items: int,
            connected_items: int,
            isolated_items: int,
            integration_index: float (0-1),
            warning: str or None,
        }
    Fails open (returns index=0) on any error.
    """
    result: Dict[str, Any] = {
        "total_items": 0,
        "connected_items": 0,
        "isolated_items": 0,
        "integration_index": 0.0,
        "warning": None,
    }
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()

        # Get all valid item IDs
        all_ids: set = set()
        for tbl in ("lessons", "failures", "patterns", "facts"):
            try:
                rows = conn.execute(
                    f"SELECT id FROM {tbl} WHERE validity = 'valid'"
                ).fetchall()
                for row in rows:
                    try:
                        all_ids.add(str(row[0]))
                    except Exception:
                        pass
            except Exception:
                pass

        if not all_ids:
            return result

        # Get IDs that appear in graph edges
        connected_ids: set = set()
        try:
            rows = conn.execute(
                "SELECT DISTINCT from_node FROM graph_edges "
                "UNION SELECT DISTINCT to_node FROM graph_edges"
            ).fetchall()
            for row in rows:
                try:
                    connected_ids.add(str(row[0]))
                except Exception:
                    pass
        except Exception:
            pass  # graph_edges may not exist — fail open

        # Intersect with valid items
        connected = all_ids & connected_ids
        total = len(all_ids)
        connected_count = len(connected)
        isolated = total - connected_count
        integration = round(connected_count / total, 3) if total > 0 else 0.0

        warning = None
        if total >= 20 and integration < 0.2:
            warning = (
                f"!! LOW INTEGRATION: Only {integration*100:.1f}% of brain items are "
                "connected via graph edges. Brain may be fragmented."
            )

        result.update({
            "total_items": total,
            "connected_items": connected_count,
            "isolated_items": isolated,
            "integration_index": integration,
            "warning": warning,
        })

    except Exception as exc:
        log.debug("get_integration_index failed: %s", exc)

    return result
