#!/usr/bin/env python3
"""Causal discovery: Learn structure from data using PC and consensus.

Demonstrates:
1. Single-algorithm discovery (PC).
2. Multi-algorithm consensus (PC + GES).
3. D-separation validation against data.
"""

from orxaq.orchestration.integration import OrxaqEngine

engine = OrxaqEngine()
engine.load_credit_ontology()
data = engine.generate_synthetic(n=2000, seed=42)

# --- PC Algorithm (constraint-based) ---
variables = ["unemployment_rate", "income", "credit_score", "default_rate", "gdp_growth"]
pc_result = engine.discover_structure(data, variables=variables, alpha=0.05, use_consensus=False)
print(f"PC Discovery: {len(pc_result.skeleton)} skeleton edges")
print(f"  CI tests run: {pc_result.ci_tests_run}")
print(f"  Oriented: {len(pc_result.oriented)}")
for a, b in sorted(pc_result.skeleton):
    if (a, b) in pc_result.oriented:
        arrow = "->"
    elif (b, a) in pc_result.oriented:
        arrow = "<-"
    else:
        arrow = "--"
    print(f"  {a} {arrow} {b}")

# --- Multi-Algorithm Consensus ---
print("\n--- Consensus Discovery ---")
consensus = engine.discover_structure(data, variables=variables, alpha=0.05, use_consensus=True)
print(f"Consensus: {len(consensus.edges)} edges")
for edge in consensus.edges:
    arrow = "->" if edge.directed else "--"
    supporters = ",".join(edge.supporters)
    print(f"  {edge.source} {arrow} {edge.target}  [{edge.confidence}]  ({supporters})")

# --- D-Separation Validation ---
print("\n--- D-Separation Validation ---")
report = engine.validate_dag(data, alpha=0.05)
status = "PASSED" if report.passed else "FAILED"
print(f"Validation: {status}")
print(f"  Implications tested: {report.total_implications}")
print(f"  Violations: {report.violations}")
print(f"  Violation rate: {report.violation_rate:.2%}")
