#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Consolidation Mid-Stages Runner: stages 11-15.

Extracted from consolidation_late_stages.py per Law 7.
"""
import logging
log = logging.getLogger("pulse.daemons.consolidation.consolidation_mid_stages")

def run_mid_stages(verbose: bool = False) -> dict:
    results = {}

    # Stage 11: Causal Graph Reasoning (Phase 4B-4D — confounders + analogy scan)
    print("[CONSOLIDATION] Stage 11: Causal Graph Reasoning")
    try:
        from pulse.graph.causal_model import detect_confounders
        confounded = detect_confounders()
        causal_result = {"confounders_found": len(confounded), "pairs": [list(p) for p in confounded[:10]]}

        from pulse.core.brain_db import get_conn
        conn = get_conn()
        top_nodes = conn.execute(
            "SELECT id, domain FROM graph_nodes ORDER BY degree DESC LIMIT 20"
        ).fetchall()
        analogy_matches = 0
        if len(top_nodes) >= 2:
            from pulse.graph.analogy import build_analogy
            seen = set()
            for i, n1 in enumerate(top_nodes):
                for n2 in top_nodes[i+1:]:
                    if n1["domain"] == n2["domain"]: continue
                    pair_key = tuple(sorted([n1["id"], n2["id"]]))
                    if pair_key in seen: continue
                    seen.add(pair_key)
                    res = build_analogy(n1["id"], n2["id"])
                    if res.get("match"): analogy_matches += 1
                    if analogy_matches >= 5 or len(seen) >= 30: break
                if analogy_matches >= 5 or len(seen) >= 30: break
        causal_result["analogy_matches"] = analogy_matches
        results["stage_11_causal_graph"] = causal_result
    except Exception as e:
        results["stage_11_causal_graph"] = {"status": "error", "error": str(e)}

    # Stage 12: Goal Generation (Phase 5A)
    print("[CONSOLIDATION] Stage 12: Goal Generation")
    try:
        from pulse.daemons.synthesis.planning.goal_engine import formulate_goals
        results["stage_12_goals"] = formulate_goals(verbose=verbose)
    except Exception as e:
        results["stage_12_goals"] = {"status": "error", "error": str(e)}

    # Stage 13: Prospective Memory Check (Phase 5B)
    print("[CONSOLIDATION] Stage 13: Prospective Memory")
    try:
        from pulse.daemons.synthesis.planning.prospective_memory import check_intentions
        results["stage_13_prospective"] = check_intentions(verbose=verbose)
    except Exception as e:
        results["stage_13_prospective"] = {"status": "error", "error": str(e)}

    # Stage 14: Sentinel Health Checks (Phase 5C)
    print("[CONSOLIDATION] Stage 14: Sentinel Checks")
    try:
        from pulse.admin.audit.sentinels import run_sentinels
        results["stage_14_sentinels"] = run_sentinels(verbose=verbose)
    except Exception as e:
        results["stage_14_sentinels"] = {"status": "error", "error": str(e)}

    # Stage 15: Autonomy Promotion Check (Phase 5D)
    print("[CONSOLIDATION] Stage 15: Autonomy Check")
    try:
        from pulse.core.autonomy_state import check_promotion
        results["stage_15_autonomy"] = {"promoted": check_promotion()}
    except Exception as e:
        results["stage_15_autonomy"] = {"status": "error", "error": str(e)}

    return results
