import requests
from flask import current_app


def _quran_config():
    return {
        'oauth_base': current_app.config['QURAN_OAUTH_BASE'],
        'api_base': current_app.config['QURAN_API_BASE'],
        'client_id': current_app.config.get('QURAN_CLIENT_ID'),
        'client_secret': current_app.config.get('QURAN_CLIENT_SECRET'),
    }


def get_access_token():
    """Get OAuth2 access token using client credentials."""
    config = _quran_config()
    if not config['client_id'] or not config['client_secret']:
        return None
    token_url = f"{config['oauth_base']}/oauth2/token"
    response = requests.post(
        token_url,
        auth=(config['client_id'], config['client_secret']),
        data={'grant_type': 'client_credentials', 'scope': 'content'},
        headers={'Content-Type': 'application/x-www-form-urlencoded'},
        timeout=10
    )
    response.raise_for_status()
    return response.json().get('access_token')


def quran_request(endpoint, params=None):
    """Make authenticated request to Quran API."""
    config = _quran_config()
    token = get_access_token()
    url = f"{config['api_base']}{endpoint}"
    headers = {}
    if token:
        headers = {
            'x-auth-token': token,
            'x-client-id': config['client_id'],
        }
    response = requests.get(
        url,
        headers=headers,
        params=params,
        timeout=15
    )
    response.raise_for_status()
    return response.json()


def get_chapters(language='id'):
    """Get list of all chapters (surah)."""
    data = quran_request('/chapters', params={'language': language})
    return data.get('chapters', [])


def get_verses(chapter_number, page=1, per_page=15, translations=None, audio=None):
    """Get verses for a specific chapter."""
    params = {
        'language': 'id',
        'page': page,
        'per_page': per_page,
        'fields': 'text_uthmani,text_imlaei,translations',
        'words': 'true',
    }
    if translations:
        params['translations'] = translations
    else:
        params['translations'] = '33'  # Indonesian Islamic Affairs Ministry
    if audio:
        params['audio'] = audio
    data = quran_request(f'/verses/by_chapter/{chapter_number}', params=params)
    return data


def get_verse_by_key(verse_key, translations=None):
    """Get a single verse by key (e.g. '1:1')."""
    params = {'language': 'id'}
    if translations:
        params['translations'] = translations
    endpoint = f'/verses/{verse_key}'
    data = quran_request(endpoint, params=params)
    return data.get('verse')


def get_juzs():
    """Get list of all juz."""
    data = quran_request('/juzs')
    return data.get('juzs', [])


def get_translations():
    """Get available translations."""
    data = quran_request('/resources/translations')
    return data.get('translations', [])
