#!/usr/bin/env python3
"""Basic approval flow example using the HAX Python SDK.

This example demonstrates how to:
1. Create an approval request
2. Wait for human response (via polling)
3. Handle the approval/denial decision

Usage:
    export HAX_API_KEY="hax_live_..."
    export HAX_BASE_URL="https://your-hax-instance.com/api/v1"
    python basic_approval.py
"""

import os
import sys

from hax import HaxClient, HaxError


def main() -> None:
    # Get configuration from environment
    api_key = os.environ.get("HAX_API_KEY")
    base_url = os.environ.get("HAX_BASE_URL", "http://localhost:3000/api/v1")

    if not api_key:
        print("Error: HAX_API_KEY environment variable is required")
        sys.exit(1)

    # Initialize the client
    client = HaxClient(api_key=api_key, base_url=base_url)

    try:
        # Create an approval request
        print("Creating approval request...")
        request = client.create_request(
            type="text-approval-v1",
            title="Action Approval Required",
            description="Please review and approve or deny this action.",
            payload={
                "text": "Do you approve this action?",
                "approveLabel": "Approve",
                "denyLabel": "Deny",
                "noteLabel": "Add a note (optional)",
                "notePlaceholder": "Enter any comments here...",
            },
            expires_in_seconds=3600,  # 1 hour expiration
            metadata={"source": "basic_approval_example"},
        )

        print(f"Request created: {request.id}")
        print(f"Status: {request.status}")
        print("\nShare this URL with the approver:")
        print(f"  {request.url}")
        print("\nWaiting for response (timeout: 5 minutes)...")

        # Wait for the human to respond
        completed_request = client.wait_for_response(
            request.id,
            poll_interval=2.0,
            timeout=300,  # 5 minutes
        )

        # Handle the response
        if completed_request.is_completed:
            response = completed_request.response
            decision = response.get("decision")
            note = response.get("note", "")

            print("\nResponse received!")
            print(f"  Decision: {decision}")
            if note:
                print(f"  Note: {note}")

            if decision == "approve":
                print("\n✓ Action APPROVED - proceeding with the action...")
                # Add your approval logic here
            else:
                print("\n✗ Action DENIED - action will not be taken.")
                # Add your denial logic here

        elif completed_request.is_expired:
            print("\n⚠ Request expired before receiving a response.")

        elif completed_request.is_cancelled:
            print("\n⚠ Request was cancelled.")

    except TimeoutError:
        print("\n⚠ Timed out waiting for response.")
        # Optionally cancel the request
        client.cancel_request(request.id)
        print("Request cancelled.")

    except HaxError as e:
        print(f"\nError: {e}")
        sys.exit(1)

    finally:
        client.close()


if __name__ == "__main__":
    main()
