# -*- coding: utf-8 -*-
"""Which providers are configured, as non-secret flags.

The skin service derives the flags from the settings (the only code that reads API keys) and stores them in a tiny
file, so the Home rows can put them into their cache identity at the very first fetch after a start, before the
service published its Window properties, and without ever reading credentials.
"""
import json
import os

import xbmcvfs

AI_KEYS = ('openai_api_key', 'anthropic_api_key', 'google_api_key', 'mistral_api_key', 'groq_api_key')
_FILE = 'provider_flags.json'


def _path():
    return xbmcvfs.translatePath('special://profile/addon_data/plugin.video.milionar/' + _FILE)


def ai_available(addon):
    """Service side: reads the keys."""
    return any(addon.getSetting(key) for key in AI_KEYS)


def write_flags(flags):
    """Service side: persist the flags when they changed."""
    try:
        if read_flags() == flags:
            return
        os.makedirs(os.path.dirname(_path()), exist_ok=True)
        temporary = _path() + '.tmp'
        with open(temporary, 'w', encoding='utf-8') as handle:
            json.dump(flags, handle, separators=(',', ':'))
        os.replace(temporary, _path())
    except OSError:
        pass


def read_flags():
    try:
        with open(_path(), encoding='utf-8') as handle:
            value = json.load(handle)
        return value if isinstance(value, dict) else {}
    except (OSError, ValueError):
        return {}


def flag(name):
    return bool(read_flags().get(name))
