#!/usr/bin/env python3
"""
Kevros Governance SDK — Quick Start Example

Demonstrates the three core patterns:
1. Verify before acting (pre-flight check)
2. Attest after acting (provenance record)
3. Bind intent to outcome (prove what you meant to do)

Prerequisites:
    pip install kevros
    export KEVROS_API_KEY=kvrs_...
"""

import os
from kevros_governance import GovernanceClient, IntentType

API_KEY = os.environ.get("KEVROS_API_KEY", "")
if not API_KEY:
    print("Set KEVROS_API_KEY environment variable first.")
    print("Get your key at https://governance.taskhawktech.com")
    exit(1)

client = GovernanceClient(api_key=API_KEY)

# ---------------------------------------------------------------------------
# Pattern 1: VERIFY before acting
# ---------------------------------------------------------------------------
print("=== Pattern 1: Verify Before Acting ===\n")

result = client.verify(
    action_type="trade",
    action_payload={"symbol": "AAPL", "shares": 100, "price": 185.50},
    policy_context={"max_values": {"shares": 500, "price": 200.0}},
    agent_id="quickstart-agent",
)

print(f"Decision: {result.decision.value}")
print(f"Reason: {result.reason}")
print(f"Release token: {result.release_token[:32]}...")
print(f"Provenance hash: {result.provenance_hash[:32]}...")
print()

# Try exceeding a bound — should get CLAMP
result2 = client.verify(
    action_type="trade",
    action_payload={"symbol": "TSLA", "shares": 1000, "price": 250.0},
    policy_context={"max_values": {"shares": 500}},
    agent_id="quickstart-agent",
)

print(f"Decision: {result2.decision.value}")  # CLAMP
print(f"Reason: {result2.reason}")
print(f"Applied action: {result2.applied_action}")  # shares clamped to 500
print()

# ---------------------------------------------------------------------------
# Pattern 2: ATTEST after acting
# ---------------------------------------------------------------------------
print("=== Pattern 2: Attest After Acting ===\n")

attestation = client.attest(
    agent_id="quickstart-agent",
    action_description="Executed AAPL buy order via Alpaca API",
    action_payload={
        "symbol": "AAPL",
        "shares": 100,
        "filled_price": 185.42,
        "order_id": "ord_abc123",
    },
    context={
        "broker": "Alpaca",
        "strategy": "momentum",
        "confidence": 0.87,
    },
)

print(f"Attestation ID: {attestation.attestation_id}")
print(f"Hash chain: {attestation.hash_prev[:16]}... -> {attestation.hash_curr[:16]}...")
print(f"Chain length: {attestation.chain_length}")
print()

# ---------------------------------------------------------------------------
# Pattern 3: BIND intent to outcome
# ---------------------------------------------------------------------------
print("=== Pattern 3: Intent Binding ===\n")

# Step 1: Declare intent and bind to command
binding = client.bind(
    agent_id="quickstart-agent",
    intent_type=IntentType.AUTOMATED,
    intent_description="Rebalance portfolio to 60/40 stocks/bonds",
    command_payload={
        "sell": [{"symbol": "SPY", "shares": 50}],
        "buy": [{"symbol": "BND", "shares": 100}],
    },
    goal_state={
        "stock_pct": 60.0,
        "bond_pct": 40.0,
    },
)

print(f"Intent ID: {binding.intent_id}")
print(f"Binding HMAC: {binding.binding_hmac[:32]}...")
print()

# Step 2: Execute the action (your code here)
# ...

# Step 3: Verify the outcome matched the intent
outcome = client.verify_outcome(
    agent_id="quickstart-agent",
    intent_id=binding.intent_id,
    binding_id=binding.binding_id,
    actual_state={
        "stock_pct": 59.8,
        "bond_pct": 40.2,
    },
    tolerance=0.05,  # 5% tolerance
)

print(f"Outcome: {outcome.status.value}")
print(f"Achieved: {outcome.achieved_percentage}%")
print(f"Evidence hash: {outcome.evidence_hash[:32]}...")
print()

# ---------------------------------------------------------------------------
# Compliance bundle
# ---------------------------------------------------------------------------
print("=== Compliance Bundle ===\n")

bundle = client.bundle(agent_id="quickstart-agent")

print(f"Bundle ID: {bundle.bundle_id}")
print(f"Records: {bundle.record_count}")
print(f"Chain intact: {bundle.chain_integrity}")
print(f"Bundle hash: {bundle.bundle_hash[:32]}...")
print()

# Health check
health = client.health()
print(f"Gateway: {health.status} (chain: {health.chain_length} records)")
