# -*- coding: utf-8 -*-
"""
Override the core IAP tools to block ALL external API calls.
This is the master switch that blocks ALL Odoo external communications.
"""

import logging
from odoo import exceptions, _

_logger = logging.getLogger(__name__)

# Store original function reference
_original_iap_jsonrpc = None


def _disabled_iap_jsonrpc(url, method='call', params=None, timeout=15):
    """
    DISABLED: Block all IAP JSON-RPC calls.
    Returns empty/success response instead of making external calls.
    """
    _logger.info("IAP JSONRPC BLOCKED: %s (method=%s)", url, method)
    
    # Return appropriate empty responses based on the endpoint
    if '/authorize' in url:
        return 'fake_transaction_token_disabled'
    elif '/capture' in url or '/cancel' in url:
        return True
    elif '/credits' in url:
        return 999999
    elif 'partner-autocomplete' in url:
        return []
    elif 'enrich' in url:
        return {}
    elif 'sms' in url:
        _logger.warning("SMS API call blocked - SMS will not be sent")
        return {'state': 'success', 'credits': 999999}
    elif 'extract' in url:
        return {'status': 'success', 'credits': 999999}
    else:
        return {}


def patch_iap_tools():
    """
    Monkey-patch the iap_jsonrpc function to block external calls.
    This is called when the module loads.
    """
    global _original_iap_jsonrpc
    
    try:
        from odoo.addons.iap.tools import iap_tools
        
        if _original_iap_jsonrpc is None:
            _original_iap_jsonrpc = iap_tools.iap_jsonrpc
        
        iap_tools.iap_jsonrpc = _disabled_iap_jsonrpc
        _logger.info("IAP JSON-RPC calls have been DISABLED globally")
        
    except ImportError:
        _logger.debug("IAP module not installed, skipping patch")
    except Exception as e:
        _logger.warning("Could not patch IAP tools: %s", e)


# Apply patch when module is imported
patch_iap_tools()

