"""Live webhook test — run with ngrok tunnel on port 5678."""

from flask import Flask, request as flask_request
from primitif import Primitif

NGROK_URL = "https://78e6348ef3da.ngrok.app"

app = Flask(__name__)
p = Primitif(api_key="ns_live_9caf029ea87d4cd94691e108ed386a43")


@p.approval.require_approval(callback_url=f"{NGROK_URL}/webhook")
def send_invoice(client, amount):
    print(f"\n>>> TOOL EXECUTED: Invoice sent to {client} for ${amount}")
    return f"Invoice sent to {client} for ${amount}"


@app.post("/webhook")
def handle_webhook():
    event = flask_request.get_json(force=True)
    print(f"\n=== Webhook received ===")
    print(f"Payload: {event}")

    try:
        result = p.approval.dispatch(event)
        print(f"Dispatch result: {result}")
    except Exception as e:
        print(f"Dispatch error: {e}")

    return "", 200


if __name__ == "__main__":
    print("=== Creating approval request ===")
    result = send_invoice("Acme", 45000)
    print(f"Status: {result.status}")
    print(f"ID: {result.id}")
    print(f"Approval URL: {result.approval_url}")
    print(f"\nOpen the approval URL in your browser and approve it.")
    print(f"Webhook will fire to {NGROK_URL}/webhook\n")

    # Run Flask on port 5678
    app.run(port=8000, debug=False)
