import httpx
from typing import Dict, Any
from .api import _base_url, _auth_headers, _debug_request, _debug_response

def execute_autonomous_charge(
    token: str,
    payer_did: str, 
    payee_did: str, 
    amount: float, 
) -> Dict[str, Any]:
    """
    Called by an autonomous AI (like ClawdBot) to instantly pay another agent.
    This hits the 'stripe-charge-autonomous' Supabase Edge Function to route
    fiat money from the Payer's saved Stripe card directly to the Payee's connected account.
    
    Args:
        token: Authenticated User JWT
        payer_did: The B2Alpha Agent ID of the agent spending the money.
        payee_did: The B2Alpha Agent ID of the business receiving the money.
        amount: The float amount in USD to charge (e.g., 50.00).
    """
    url = f"{_base_url()}/stripe-charge-autonomous"
    headers = _auth_headers(token)
    
    payload = {
        "payer_agent_id": payer_did,
        "payee_agent_id": payee_did,
        "amount": amount
    }

    _debug_request("POST", url, headers, payload)
    resp = httpx.post(url, headers=headers, json=payload, timeout=20)
    _debug_response(resp)
        
    try:
        data = resp.json()
    except:
        raise RuntimeError(f"Critical Backend Failure. Could not parse response: {resp.text}")

    if resp.status_code != 200:
        error_msg = data.get('error') or data.get('message') or "Unknown Error"
        raise RuntimeError(f"Payment Declined or Failed: {error_msg}")
        
    return data

def get_onboarding_url(token: str, agent_did: str) -> str:
    """
    Hit the 'stripe-onboard-business' function to generate a secure link
    for the human owner of the agent to complete their Stripe KYC.
    """
    url = f"{_base_url()}/stripe-onboard-business"
    headers = _auth_headers(token)
    payload = {"agent_id": agent_did}

    _debug_request("POST", url, headers, payload)
    resp = httpx.post(url, headers=headers, json=payload, timeout=20)
    _debug_response(resp)

    try:
        data = resp.json()
    except:
        raise RuntimeError(f"Critical Backend Failure: {resp.text}")

    if resp.status_code != 200:
        raise RuntimeError(f"Onboarding Failed: {data.get('error', 'Unknown Error')}")

    return data.get("url")
