#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Stages 4/4c: Knowledge graph update and abstraction schema creation."""


def stage_graph_update(verbose=False):
    """Stage 4: Rebuild knowledge graph from current brain state."""
    try:
        from pulse.graph.knowledge_graph import incremental_update
        result = incremental_update(verbose=verbose)
        node_count = result.get("metadata", {}).get("node_count", 0)
        edge_count = result.get("metadata", {}).get("edge_count", 0)
        if verbose:
            print(f"  [GRAPH] Updated: {node_count} nodes, {edge_count} edges")
        return {"status": "ok", "nodes": node_count, "edges": edge_count}
    except ImportError:
        if verbose:
            print("  [GRAPH] knowledge_graph.py not available")
        return {"status": "skipped", "reason": "knowledge_graph not available"}
    except Exception as e:
        if verbose:
            print(f"  [GRAPH] Error: {e}")
        return {"status": "error", "error": str(e)}


def stage_4c_abstraction(verbose=False):
    """Stage 4c: Anti-unification — abstract structurally identical causal subgraphs."""
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        query = """
            SELECT group_concat(e.from_node) as similar_nodes, e.to_node,
                   COUNT(e.from_node) as instance_count
            FROM graph_edges e
            WHERE e.edge_type = 'CAUSES'
            GROUP BY e.to_node
            HAVING instance_count >= 3
        """
        schemas_created = 0
        with conn:
            for row in conn.execute(query).fetchall():
                target = row["to_node"]
                schema_id = f"SCHEMA_{target}"
                if conn.execute("SELECT 1 FROM graph_nodes WHERE id = ?", (schema_id,)).fetchone():
                    continue
                conn.execute(
                    "INSERT INTO graph_nodes (id, type, text) VALUES (?, 'SCHEMA', ?)",
                    (schema_id, f"Abstract schema for causes of {target}"),
                )
                conn.execute(
                    "INSERT INTO graph_edges (from_node, to_node, edge_type, confidence) VALUES (?, ?, 'CAUSES', 0.9)",
                    (schema_id, target),
                )
                for inst in row["similar_nodes"].split(","):
                    conn.execute(
                        "INSERT INTO graph_edges (from_node, to_node, edge_type, confidence) VALUES (?, ?, 'INSTANCE_OF', 0.9)",
                        (inst, schema_id),
                    )
                schemas_created += 1
        if verbose:
            print(f"  [4C] Created {schemas_created} abstract causal schemas.")
        return {"schemas_created": schemas_created}
    except ImportError:
        if verbose:
            print("  [4C] SQLite DAL not fully loaded")
        return {"status": "skipped"}
    except Exception as e:
        if verbose:
            print(f"  [4C] Error: {e}")
        return {"error": str(e)}
