import json

import requests

from cc_py_commons.utils import json_logger
from .constants import C4_API_AUTH_TOKEN, C4_API_URL
from . import c4_cache


def execute(account_id, integration_type, request_id=None):
	"""
	Get integration settings for an account.

	This function checks the Redis cache first (if enabled) and falls back to
	the C4 API if the cache is empty or unavailable.

	Args:
		account_id: The account ID
		integration_type: The integration type (e.g., 'TAI')
		request_id: Optional request ID for tracing

	Returns:
		The integration response dict, False if not found, or None on error
	"""
	# Check cache first (with fallback on any error)
	try:
		cached = c4_cache.get_cached_integration(account_id, integration_type)

		if cached is not None:
			json_logger.debug(account_id, "Integration cache hit", integration_type=integration_type)
			return cached

	except Exception as e:
		json_logger.warning(account_id, "Cache read error, falling back to API", error=str(e))

	# Fetch from API
	result = _fetch_from_api(account_id, integration_type, request_id)

	# Cache successful responses (including "not found" responses to avoid repeated lookups)
	if result is not None:

		try:
			c4_cache.cache_integration(account_id, integration_type, result)

		except Exception as e:
			json_logger.warning(account_id, "Cache write error", error=str(e))

	return result


def _fetch_from_api(account_id, integration_type, request_id=None):
	"""
	Fetch integration settings directly from the C4 API.

	Args:
		account_id: The account ID
		integration_type: The integration type (e.g., 'TAI')
		request_id: Optional request ID for tracing

	Returns:
		The integration response dict, False if not found, or None on error
	"""
	url = f"{C4_API_URL}/integrations"
	token = f"Bearer {C4_API_AUTH_TOKEN}"
	headers = {
		"Authorization": token
	}
	params = {
		'accountId': account_id,
		'integrationType': integration_type,
		'requestId': request_id
	}
	json_logger.debug(account_id, "Getting integration from API", url=url, params=params)

	try:
		response = requests.get(url, headers=headers, params=params, timeout=30)

	except requests.RequestException as e:
		json_logger.warning(account_id, "Request to get account integration failed", error=str(e))
		return None

	if response.status_code != 200:
		json_logger.warning(account_id, "Request to get account integration failed", status_code=response.status_code)
		return None

	try:
		json_response = response.json()

	except (ValueError, json.JSONDecodeError) as e:
		json_logger.warning(account_id, "Failed to parse integration response", error=str(e))
		return None

	if json_response.get('code') != 200:
		json_logger.warning(account_id, "Unable to find integration", integration_type=integration_type)
		return False

	return json_response
