# -*- coding: utf-8 -*-
"""
Created on Mon Jan 26 09:05:52 2026

@author: adria
"""

import os 
import yaml 
import sys
import logging 

from ..utils import search_fp_obj

# Variables

DEFAULT_SECRET_NAME = 'ec2_london_pem'

LOCAL_PATH = os.environ['USERPROFILE'] if 'USERPROFILE' in os.environ else os.environ['HOME']
CREDENTIALS_PATH_SUFFIX = 'creds'
CREDENTIALS_PATHS = [os.path.join(LOCAL_PATH, CREDENTIALS_PATH_SUFFIX)]
CREDENTIALS_FILE = 'creds.yaml'
CREDENTIALS_FILENAME = 'local credentials file'

logger = logging.getLogger(__name__)


# Functions   

def _load_credentials_from_file(credentials_fp):
    try:
        if credentials_fp is None:
            credentials_fp = search_fp_obj(
                target_fp_obj = CREDENTIALS_FILE,
                search_paths = CREDENTIALS_PATHS,
                target_fp_obj_name = CREDENTIALS_FILENAME
                )
            
        with open(credentials_fp) as fin:
            credentials = yaml.safe_load(fin)
    except Exception as e:
        logger.error(
            f'unable to load credentials from the local file {credentials_fp!r} '
            f'due to the following error: {e.__class__.__name__}: {e}'
        )
        return {}, credentials_fp
    else:
        return credentials, credentials_fp
    

def _key_from_credentials(key_name, credentials):
    if key_name is None:
        return credentials
    else:
        try:
            return credentials[key_name]
        except KeyError:
            cred_keys = credentials.key()
            if key_name not in cred_keys:
                ke = KeyError(
                    f' `key_name` mut be one of {list(cred_keys)} for the given'
                    f'credentials, but {key_name!r} was passed'
                )
                logger.error(f'{ke.__class__.__name__}: {ke}')
                raise ke 
    
    
def load_credentials(
        key_name = None,
        credentials_fp = None,
        secret_name = None,
        aws_credentials_fp = None
    ):
    """
    Loads the credentias to use the module classes. 
    
    If given a path to a local yaml or json file, it loads the credentials from the given file.
    Otherwise, it tries to load the credentias as environ variables. I we give a key_name, we can
    get just the credentials referred in the key_name instead of load all the credentials
    
    Note: This functions is currently incomplete: It's made for, if we need it, add more ways to load
    credentials, such as from secrets manager, keys or api_creds
    """ 
    
    # from local file
    credentials, credentials_fp = _load_credentials_from_file(credentials_fp)
    if credentials:
        logger.debug(f'loaded credentials from local file {credentials_fp!r}')
        return _key_from_credentials(key_name, credentials)
    
    ve = ValueError('unable to load credentias with the given configuration')
    logger.error(ve)
    raise ve
    
    
