"""Example: Graph enrichment in SDK workflows.

Demonstrates:
    1. Enabling IKE and formula graph integration
    2. Running a workflow and inspecting graph context
    3. Using GraphProbe for readiness checks
    4. Overriding fallback policy per-workflow

Prerequisites:
    - Set ``SDK_ENABLE_IKE_GRAPH=true`` and ``SDK_ENABLE_FORMULA_GRAPH=true``
    - IKE service running at ``SDK_IKE_ENDPOINT``
"""

from __future__ import annotations

from sdk import SolutionBuilder, SDKConfig
from databridge_core.sdk.core.graph_probe import GraphProbe


def main() -> None:
    # 1. Configure with graph integration enabled
    config = SDKConfig(
        enable_graphs=True,
        enable_ike=True,
        enable_ike_graph=True,
        enable_formula_graph=True,
        ike_endpoint="http://localhost:8000",
        graph_fallback_policy="best_effort",
    )

    with SolutionBuilder(config=config, user_id="demo@example.com") as builder:
        # 2. Check graph health before running workflows
        health = builder.graph_health()
        print(f"Graph health: {health['overall']}")
        print(f"  Reachable: {health['reachable_count']}/{health['enabled_count']}")
        for name, status in health["systems"].items():
            if status["enabled"]:
                mark = "OK" if status["reachable"] else "FAIL"
                print(f"  {name}: {mark} ({status['latency_ms']}ms)")

        # 3. Run a workflow — graph context is collected automatically
        #    (for workflows using GraphContextMixin)
        result = builder.run("reconciliation.hash_compare", {
            "source_a_path": "gl.csv",
            "source_b_path": "tb.csv",
            "key_columns": "account_id",
        })

        # 4. Inspect graph context from the result
        gctx = result.metadata.get("graph_context", {})
        print(f"\nGraph context available: {gctx.get('available')}")
        print(f"  IKE graph: {'collected' if gctx.get('ike_graph') else 'none'}")
        print(f"  Formula graph: {'collected' if gctx.get('formula_graph') else 'none'}")
        print(f"  Lineage nodes: {len(gctx.get('lineage_nodes', []))}")
        print(f"  Errors: {gctx.get('errors', {})}")
        print(f"  Trace ID: {gctx.get('trace_id')}")

        # 5. Override fallback policy for a specific run
        result_strict = builder.run("detection.grounded_detection", {
            "file_path": "data.csv",
            "graph_fallback_policy": "strict",  # raises on graph errors
        })
        print(f"\nStrict run status: {result_strict.status.value}")


if __name__ == "__main__":
    main()
