#!/usr/bin/env python3
"""06 — Decision tracing with context graphs.

Record agent decisions into a graph database for auditing and precedent search.

Requirements:
    pip install koan[graph]
    # Start Neo4j: docker compose -f docker/docker-compose.graph.yml --profile neo4j up -d
    # Initialize schema: koan graph init --password koan-dev-password
"""

from __future__ import annotations

import asyncio

from koan.graph import DecisionTracer, GraphConfig, create_graph_client, get_run_trace


async def main() -> None:
    # Connect to the graph database
    config = GraphConfig(
        provider="neo4j",
        uri="bolt://localhost:7687",
        username="neo4j",
        password="koan-dev-password",
    )

    async with create_graph_client(config) as client:
        # Record a decision trace
        async with DecisionTracer(
            client,
            run_id="demo-run-001",
            agent_id="support-agent",
            thread_id="ticket-42",
        ) as tracer:
            # Record a classification decision
            decision_id = await tracer.record_decision(
                description="Classified ticket as billing inquiry",
                decision_type="classification",
                confidence=0.92,
                reasoning="Keywords: 'invoice', 'payment due'",
            )

            # Record the action taken
            await tracer.record_action(
                decision_id=decision_id,
                action_type="tool_call",
                tool_name="lookup_billing",
            )

            # Link to a business entity
            await tracer.link_entity(
                decision_id=decision_id,
                entity_id="acct-1234",
                entity_type="account",
                source_system="crm",
            )

            # Record the outcome
            await tracer.record_outcome(
                status="success",
                result="Billing inquiry resolved",
                evaluation_score=0.95,
            )

        # Query the trace back
        trace = await get_run_trace(client, "demo-run-001")
        print(f"Trace contains {len(trace)} records:")
        for record in trace:
            print(f"  {record.data}")


if __name__ == "__main__":
    asyncio.run(main())
