import logging
import requests

logger = logging.getLogger(__name__)

REQUEST_TIMEOUT = 5


def ship_heartbeat(api_key: str, service_name: str, environment: str, metrics: dict, api_url: str, daemon_version: str = '0.1.0'):
    payload = {
        'service_name': service_name,
        'environment': environment,
        'stack': 'unknown',
        'language': 'unknown',
        'daemon_version': daemon_version,
        'metrics': metrics,
    }
    _post(api_key, f'{api_url}/heartbeat/', payload)


def ship_traces(api_key: str, spans: list, api_url: str):
    if not spans:
        return
    _post(api_key, f'{api_url}/traces/', {'spans': spans})


def _post(api_key: str, url: str, payload: dict) -> None:
    if not url.startswith('https://'):
        logger.error('Refusing to send data over non-HTTPS URL: %s', url.split('/', 3)[:3])
        return
    try:
        response = requests.post(
            url,
            json=payload,
            headers={'X-API-Key': api_key, 'Content-Type': 'application/json'},
            timeout=REQUEST_TIMEOUT,
        )
        if not response.ok:
            logger.warning('South Star API returned %s: %s', response.status_code, response.text[:200])
    except requests.exceptions.ConnectionError:
        logger.debug('Could not reach South Star API — will retry next cycle.')
    except Exception as exc:
        logger.warning('Unexpected error shipping data: %s', exc)
