import os

from speedbuild.auth.cli_utils import get_config

provider_to_api_key_name = {
    "openai":"OPENAI_API_KEY",
    "anthropic":"ANTHROPIC_API_KEY",
    "google":"GEMINI_API_KEY",
    "gemini":"GEMINI_API_KEY"
}

def getProviderAPIKey(provider):
    if provider == None:
        return None
    return os.environ.get(provider_to_api_key_name[provider],None)

def getLLMConfig():
    model_provider = os.environ.get("speedbuild_model_provider",None)
    model_name = os.environ.get("speedbuild_model_name",None)
    provider_key = getProviderAPIKey(model_provider)

    if model_provider == None:
        raise ValueError("Model provider has not been specified")
    
    if model_name == None:
        raise ValueError("Model name has not been specified")
    
    if provider_key == None:
        raise ValueError(f"API key for model provider {model_provider} has not been set")
    
    return [model_provider,model_name]


def setSpeedbuildConfig():
    config = get_config()
    config_keys = config.keys()

    if "default_model" in config_keys:
        model_name = os.environ.get("speedbuild_model_name",None)
        model_name_in_config = config['default_model']
        
        if model_name_in_config != model_name:
            os.environ['speedbuild_model_name'] = model_name_in_config

    if "model_provider" in config_keys:
        model_provider = os.environ.get("speedbuild_model_provider",None)

        if config['model_provider'] != model_provider:
            os.environ["speedbuild_model_provider"] = config["model_provider"]

    if "llm_keys" in config_keys and "model_provider" in config_keys:
        model_provider = config['model_provider']
        key_config = config["llm_keys"]

        provider_key = getProviderAPIKey(model_provider)
        key_name = provider_to_api_key_name[model_provider]

        if provider_key != key_config[model_provider]:
            os.environ[key_name] = key_config[model_provider]