#!/usr/bin/env python3
"""08 — Search past decisions for precedent.

Query the context graph for similar past decisions to inform current choices.

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,
    PrecedentSearch,
    create_graph_client,
)


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

    async with create_graph_client(config) as client:
        # First, seed some precedent decisions
        for i in range(3):
            async with DecisionTracer(
                client,
                run_id=f"precedent-run-{i}",
                agent_id="support-agent",
                thread_id=f"ticket-{100 + i}",
            ) as tracer:
                decision_id = await tracer.record_decision(
                    description=f"Granted exception #{i + 1} for late payment",
                    decision_type="exception",
                    confidence=0.8 + (i * 0.05),
                    reasoning="Customer has good standing",
                )

                await tracer.link_entity(
                    decision_id=decision_id,
                    entity_id="acct-VIP-001",
                    entity_type="account",
                    source_system="crm",
                )

                await tracer.record_outcome(
                    status="success" if i < 2 else "partial",
                    evaluation_score=0.85 + (i * 0.03),
                )

        # Now search for precedents
        search = PrecedentSearch(client)

        results = await search.find(
            entity_id="acct-VIP-001",
            decision_type="exception",
            min_confidence=0.75,
            limit=10,
        )

        print(f"Found {len(results)} precedent decisions:\n")
        for r in results:
            print(f"  Decision: {r.description}")
            print(f"  Confidence: {r.confidence:.0%}")
            print(f"  Outcome: {r.outcome_status}")
            print(f"  Score: {r.evaluation_score}")
            print()


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