import json
import os
import sys

import pytest

test_config_whitelist = ['iMio (basic)']


# TODO : Compare config.json "theme_color" value with "_vars.scss "$theme-color" value and check if they are the same.
# TODO : check that config.json has "variables": {"email_header_asset" : 'emails:logo'}.
# TODO : check that all "label": [...] values string has a firt letter in uppercase (except for some expressions whitelisted in a list).
# TODO : check that all "variables": {"theme_color" : [...]} respect the format "#XXXXXX" with capital letters.


def get_config_files():
    """Get all config.json files from the ./static directory."""
    config_files = []
    for root, dirs, files in os.walk('./static'):
        for file in files:
            if file == 'config.json':
                config_files.append(os.path.join(root, file))
    return config_files


def check_spaces_in_strings(obj, file_path):
    """Recursively check for extra spaces in strings within a JSON object."""
    if isinstance(obj, dict):
        for key, value in obj.items():
            check_spaces_in_strings(value, file_path)
    elif isinstance(obj, list):
        for item in obj:
            check_spaces_in_strings(item, file_path)
    elif isinstance(obj, str):
        assert obj == obj.strip(), f"⚠️ Extra spaces in string '{obj}' in {file_path} ⚠️"


def check_config(file_path):
    """Perform the required checks on a config.json file."""
    with open(file_path, 'r') as file:
        data = json.load(file)

        # Skip check if label is 'iMio (basic)'
        if data.get('label') in test_config_whitelist:
            return True

        # Check COMBO_MAP_DEFAULT_POSITION exists
        combo_map = data.get('settings', {}).get('combo', {}).get('COMBO_MAP_DEFAULT_POSITION', None)
        assert combo_map is not None, f'COMBO_MAP_DEFAULT_POSITION not found in {file_path}'

        # Check lat and lng values
        lat = combo_map.get('lat')
        lng = combo_map.get('lng')
        assert lat != '50.49886009459319', f'⚠️ Invalid lat value in {file_path} ⚠️'
        assert lng != '4.7199939932529755', f'⚠️ Invalid lng value in {file_path} ⚠️'

        # Check favicon value
        favicon = data.get('variables', {}).get('favicon', '')
        assert 'imio-basic' not in favicon, f'⚠️ Invalid favicon value in {file_path} ⚠️'

        # Check for extra spaces in strings
        check_spaces_in_strings(data, file_path)

        return True


@pytest.mark.parametrize('file_path', get_config_files())
def test_config(file_path):
    """Test each config.json file."""
    assert check_config(file_path)


if __name__ == '__main__':
    pytest.main()
