"""使用:
    from enconia_utils import Credentials
    creds = Credentials(
        access_key_id="xxx",
        access_key_secret="xxx",
        sls_project="your_project",
        sls_logstore="your_logstore",
    )
    creds.send_sls_log("script_name", "INFO", "log message")
"""

import logging
import time
from datetime import datetime

import requests
from aliyun.log import LogClient, LogItem, PutLogsRequest

logger = logging.getLogger(__name__)


def _send_log_to_sls_internal(
    script_name: str,
    level: str,
    message: str,
    endpoint: str,
    project: str,
    logstore: str,
    access_key_id: str,
    access_key_secret: str,
    **kwargs
):
    """内部实现: 发送日志到阿里云 SLS (由 Credentials.send_sls_log 调用)"""
    try:
        client = LogClient(endpoint, access_key_id, access_key_secret)
        
        log_item = LogItem()
        log_item.set_time(int(time.time()))
        log_item.set_contents([
            ('level', level),
            ('message', message),
            ('timestamp', datetime.now().isoformat()),
            ('script', script_name),
            ('extra_info', str(kwargs) if kwargs else '')
        ])
        
        request = PutLogsRequest(project, logstore, '', '', [log_item])
        client.put_logs(request)
        logger.info(f"SLS日志发送成功: {message}")
        
    except Exception as e:
        logger.error(f"SLS SDK发送异常: {str(e)}, 尝试HTTP方式...")
        try:
            _send_log_via_http(
                script_name=script_name,
                level=level,
                message=message,
                endpoint=endpoint,
                logstore=logstore,
                **kwargs
            )
        except Exception as http_e:
            logger.error(f"HTTP方式也发送失败: {str(http_e)}")
            raise


def _send_log_via_http(
    script_name: str,
    level: str,
    message: str,
    endpoint: str,
    logstore: str,
    **kwargs
):
    """通过 HTTP API 发送日志到 SLS (降级方案)"""
    log_data = {
        'level': level,
        'message': message,
        'timestamp': datetime.now().isoformat(),
        'script': script_name,
        'extra_info': kwargs if kwargs else {}
    }
    
    headers = {
        'Content-Type': 'application/json',
        'x-log-apiversion': '0.6.0',
        'x-log-signaturemethod': 'hmac-sha1'
    }
    
    url = f"https://{endpoint}/logstores/{logstore}/shards/lb"
    response = requests.post(url, headers=headers, json=log_data, timeout=5)
    
    if response.status_code == 200:
        logger.info(f"HTTP方式SLS日志发送成功: {message}")
    else:
        raise RuntimeError(f"HTTP方式SLS日志发送失败: 状态码={response.status_code}, 响应={response.text[:200]}")
