// Written by retoor@molodetz.nl

// This source code retrieves an API key from environment variables or defaults
// to a hardcoded key if none are found.

// Uses the C standard library functions from stdlib.h for environment
// management and stdio.h for error handling.

// MIT License

#ifndef R_AUTH_H
#define R_AUTH_H

#include <stdio.h>
#include <stdlib.h>

enum AUTH_TYPE { AUTH_TYPE_NONE, AUTH_TYPE_API_KEY, AUTH_TYPE_FREE };

int auth_type = AUTH_TYPE_NONE;

void auth_free() { auth_type = AUTH_TYPE_FREE; }

void auth_init() {

  char *api_key = NULL;
  if (auth_type != AUTH_TYPE_FREE) {

    api_key = getenv("R_KEY");
    if (api_key) {
      auth_type = AUTH_TYPE_API_KEY;
      return;
    }
    api_key = getenv("OPENAI_API_KEY");
    if (api_key) {
      auth_type = AUTH_TYPE_API_KEY;
      return;
    }
  }
  auth_type = AUTH_TYPE_FREE;
  return;
}

const char *resolve_api_key() {
  static char *api_key = NULL;
  if (auth_type != AUTH_TYPE_FREE) {

    api_key = getenv("R_KEY");
    if (api_key) {
      auth_type = AUTH_TYPE_API_KEY;
      return api_key;
    }
    api_key = getenv("OPENAI_API_KEY");
    if (api_key) {
      auth_type = AUTH_TYPE_API_KEY;
      return api_key;
    }
  }
  auth_type = AUTH_TYPE_FREE;
  api_key = "sk-proj-d798HLfWYBeB9HT_o7isaY0s88631IaYhhOR5IVAd4D_fF-"
            "SQ5z46BCr8iDi1ang1rUmlagw55T3BlbkFJ6IOsqhAxNN9Zt6ERDBnv2p2HCc2fDgc"
            "5DsNhPxdOzYb009J6CNd4wILPsFGEoUdWo4QrZ1eOkA";
  return api_key;
}

#endif
