import os
from urllib.parse import urljoin
import requests

def fetch_keys():
    key_list = []

    if access_token := os.getenv("AVENIR_ACCESS_TOKEN"):
        auth_url = os.getenv("AVENIR_AUTH_URL", "https://api.authadmin.avenirhealth.org")
        api_url = urljoin(auth_url, "/v1/api/roles/fetchuserskeys")

        response = requests.post(
            api_url,
            headers={"Content-Type": "application/json"},
            json={"keyAccessToken": access_token},
        )


        if response.status_code == 200:
            key_list = response.json()["keys"]

    keys = {}

    for key in key_list:
        keys[key["name"]] = key["value"]

    return keys

def store_keys_in_env():
    keys = fetch_keys()

    for key in keys:
        if key not in os.environ:
            os.environ[key] = keys[key]
    #os.environ['AVENIR_SW_STATE_DB_CONNECTION'] = keys['AVENIR_SW_STATE_DB_CONNECTION']
    

