# -*- coding: utf-8 -*-
# plugin.video.alkoflix
# resources/lib/modules/alkopastes_api.py

import json

from modules import kodi_utils

API_URL = 'https://paste.lesalkodiques.com/api.php'

get_setting = kodi_utils.get_setting
logger = kodi_utils.logger


def has_user_api_key():
	try: return bool(str(get_setting('alkopastes.api_key_user', '')).strip())
	except Exception: return False


def api_key():
	return str(get_setting('alkopastes.api_key_user', '')).strip()


def _headers():
	return {
		'X-API-Key': api_key(),
		'Content-Type': 'application/json',
		'User-Agent': 'alkoFlix/%s' % kodi_utils.get_addoninfo('version')
	}


def _mask_code(code):
	code = str(code or '').strip()
	if not code: return ''
	if len(code) <= 6: return code[:2] + '***'
	return code[:3] + '***' + code[-3:]


def _request(method, action, payload=None, params=None, timeout=30.0, log_name='alkoPastes request'):
	import requests
	params = dict(params or {})
	params['action'] = action
	safe_params = dict(params)
	if 'api_key' in safe_params: safe_params['api_key'] = '***'
	if 'id' in safe_params: safe_params['id'] = _mask_code(safe_params.get('id'))
	if 'p_code' in safe_params: safe_params['p_code'] = _mask_code(safe_params.get('p_code'))
	if 'slug' in safe_params: safe_params['slug'] = _mask_code(safe_params.get('slug'))
	payload_keys = sorted(list((payload or {}).keys())) if isinstance(payload, dict) else []
	logger(log_name, 'START | method=%s | action=%s | params=%s | payload_keys=%s' % (method, action, safe_params, payload_keys))
	if method == 'GET':
		response = requests.get(API_URL, params=params, headers=_headers(), timeout=timeout)
	elif method == 'POST':
		response = requests.post(API_URL, params=params, data=json.dumps(payload or {}, ensure_ascii=False).encode('utf-8'), headers=_headers(), timeout=timeout)
	else:
		response = requests.delete(API_URL, params=params, headers=_headers(), timeout=timeout)
	try: data = response.json()
	except Exception:
		data = {'success': False, 'error': response.text[:500] if hasattr(response, 'text') else 'Réponse invalide'}
	if response.status_code not in (200, 201) or not data.get('success'):
		error = data.get('error') or data.get('message') or 'Erreur HTTP %s' % response.status_code
		logger(log_name, 'FAIL | method=%s | action=%s | status=%s | error=%s' % (method, action, response.status_code, error))
		raise Exception(error)
	logger(log_name, 'OK | method=%s | action=%s | status=%s | keys=%s' % (method, action, response.status_code, sorted(list(data.keys()))))
	return data


def _summary_code(paste):
	paste = paste or {}
	return str(paste.get('slug') or paste.get('p_code') or paste.get('id') or '').strip()


def _paste_code(result, previous_code=''):
	paste = (result or {}).get('paste') or {}
	return _summary_code(paste) or str(previous_code or '').strip()
