import requests
import json

def send_whatsapp(cliente_tel: str, ruta_archivo_local: str) -> dict:
    try:
        auth_url = "https://gateway.aivo.co/api/v1/auth"
        auth_payload = {
            "user": "david.maestre@kubico.co",
            "password": "CrediGol1at22,,,"
        }

        auth_headers = {
            "Content-Type": "application/json"
        }

        auth_response = requests.post(auth_url, headers=auth_headers, data=json.dumps(auth_payload))
        auth_response.raise_for_status()
        auth_data = auth_response.json()

        if 'Authorization' not in auth_data:
            error_msg = auth_data.get('error', {}).get('message', 'Error desconocido en la autenticación.')
            return {"success": 0, "message": f"No se recibió el token de autenticación: {error_msg}"}

        token = auth_data['Authorization']

        if not cliente_tel or not ruta_archivo_local:
            return {"success": 0, "message": "Faltan parámetros obligatorios: número de teléfono o URL del video."}

        numero_enviar = f"57{cliente_tel}"

        mensaje_payload = {
            "to": numero_enviar,
            "type": "template",
            "recipient_type": "individual",
            "campaign_id": "b9d43e1b-ee8e-4b03-a4b0-ecd0e8f17a08",
            "template": {
                "namespace": "10bbf296_ac1a_4414_9f09_39e107f7b5aa",
                "name": "habla",
                "language": {
                    "policy": "deterministic",
                    "code": "es_ES"
                },
                "components": [
                    {
                        "type": "header",
                        "parameters": [
                            {
                                "type": "video",
                                "video": {
                                    "link": ruta_archivo_local
                                }
                            }
                        ]
                    }
                ]
            }
        }

        mensaje_headers = {
            "Content-Type": "application/json",
            "Authorization": token,
            "X-Token": "TlRjNU5ERmhNbU0yWVRkaFlUZ3laRE01Tm1Nd056TTVORFE0T1RObE9URT0="
        }

        mensaje_url = "https://gateway.aivo.co/api/v1/conversation-whatsapp-native-templates"
        mensaje_response = requests.post(mensaje_url, headers=mensaje_headers, data=json.dumps(mensaje_payload))
        mensaje_response.raise_for_status()
        mensaje_data = mensaje_response.json()

        if 'error' in mensaje_data:
            error_details = mensaje_data['error'].get('error_data', {}).get('details', 'Detalles no disponibles.')
            error_message = mensaje_data['error'].get('message', 'Error desconocido.')
            error_code = mensaje_data['error'].get('code', 0)
            return {
                "success": 0,
                "message": f"Error de la API: {error_message} (Código: {error_code}). Detalles: {error_details}"
            }

        return {"success": 1, "message": "Mensaje enviado con éxito.", "Response": mensaje_data}

    except Exception as e:
        return {"success": 0, "message": str(e)}

# Este bloque se puede mantener para pruebas desde terminal
if __name__ == "__main__":
    import sys
    if len(sys.argv) != 3:
        print(json.dumps({"success": 0, "message": "Debe proporcionar cliente_tel y rutaArchivoLocal."}))
    else:
        result = send_whatsapp(sys.argv[1], sys.argv[2])
        print(json.dumps(result))
