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

This example demonstrates how to:
1. Create a confirmation request requiring a specific phrase
2. Wait for human response (via polling)
3. Handle the confirm/cancel decision

This template is useful for destructive actions where you want
the user to explicitly type a confirmation phrase (like "DELETE")
to proceed.

Usage:
    export HAX_API_KEY="hax_live_..."
    export HAX_BASE_URL="https://your-hax-instance.com/api/v1"
    python confirm_action.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 a confirmation request for a destructive action
        print("Creating confirmation request...")
        request = client.create_request(
            type="confirm-action-v1",
            title="Destructive Action Confirmation",
            description="A critical action requires your explicit confirmation.",
            payload={
                "title": "Delete Production Database",
                "message": (
                    "This will permanently delete all data in the production database. "
                    "This action cannot be undone. All user accounts, transactions, "
                    "and historical data will be permanently lost."
                ),
                "confirmPhrase": "DELETE PRODUCTION",
                "confirmLabel": "I understand, delete everything",
                "cancelLabel": "Cancel, keep the data",
                "warningLevel": "danger",
            },
            expires_in_seconds=600,  # 10 minute expiration for urgent actions
            metadata={
                "source": "confirm_action_example",
                "action_type": "database_deletion",
                "target": "production",
            },
        )

        print(f"Request created: {request.id}")
        print(f"Status: {request.status}")
        print("\nShare this URL with the person who needs to confirm:")
        print(f"  {request.url}")
        print("\nThey will need to type 'DELETE PRODUCTION' to confirm.")
        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
            action = response.get("action")
            phrase_provided = response.get("phraseProvided")

            print("\nResponse received!")
            print(f"  Action: {action}")
            if phrase_provided:
                print(f"  Phrase provided: {phrase_provided}")

            if action == "confirm":
                print("\n⚠️  Action CONFIRMED - proceeding with destructive action...")
                # Add your destructive action logic here
                # e.g., delete_production_database()
            else:
                print("\n✓ Action CANCELLED - no changes made.")
                # Add your cancellation logic here

        elif completed_request.is_expired:
            print("\n⚠ Request expired before receiving a response.")
            print("No action taken (fail-safe).")

        elif completed_request.is_cancelled:
            print("\n⚠ Request was cancelled programmatically.")
            print("No action taken.")

    except TimeoutError:
        print("\n⚠ Timed out waiting for response.")
        print("No action taken (fail-safe).")
        # 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()
