# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""SQLite-sourced node builder for the knowledge graph."""

from .graph_parser import node_id as _node_id, extract_causal_edges as _extract_causal_edges


def nodes_from_sqlite(nodes: dict, edges: list):
    """Build graph nodes from SQLite lessons/failures/facts/patterns tables using native id column."""
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        type_map = {
            "lessons": "LESSON",
            "failures": "FAILURE",
            "patterns": "PATTERN",
            "facts": "FACT",
        }
        for table, node_type in type_map.items():
            try:
                rows = conn.execute(
                    f"SELECT id, content, domain, confidence FROM {table} WHERE validity != 'archived' LIMIT 5000"
                ).fetchall()
            except Exception:
                continue
            for row in rows:
                row_id, text, domain, confidence = row[0], row[1], row[2], row[3]
                if not row_id or not text or len(str(text)) < 5:
                    continue
                nid = str(row_id)
                nodes[nid] = {
                    "id": nid, "type": node_type, "text": str(text)[:200],
                    "source": table, "confidence": float(confidence) if confidence else 0.5,
                    "domain": domain or "general",
                }
                for edge in _extract_causal_edges(str(text)):
                    from_id = _node_id(edge["from_text"])
                    to_id = _node_id(edge["to_text"])
                    if from_id not in nodes and len(edge["from_text"]) >= 20:
                        nodes[from_id] = {
                            "id": from_id, "type": "CONCEPT",
                            "text": edge["from_text"], "source": "causal_parser",
                        }
                    if to_id not in nodes and len(edge["to_text"]) >= 20:
                        nodes[to_id] = {
                            "id": to_id, "type": "CONCEPT",
                            "text": edge["to_text"], "source": "causal_parser",
                        }
                    edges.append({
                        "from": from_id, "to": to_id,
                        "type": edge["type"], "confidence": edge["confidence"],
                        "source_node": nid,
                    })
    except Exception:
        pass
