# -*- coding: utf-8 -*-
"""
Created on Mon Jan 26 09:40:43 2026

@author: adria
"""

import os
import sys
import logging

logger = logging.getLogger(__name__)

DEFAULT_NAME = 'target filepath object'

# Functions

def _search_fp_obj_upwards(target_fp_obj, path, target_fp_obj_name, n_levels):
    """
    helper (private) function to search for `target_fp_obj` in `path`,
    and up to `n_levels` levels upwards in the folder hierarchy
    """
    for i in range(n_levels):
        logger.debug(
            f'Searching for the {target_fp_obj_name} {target_fp_obj!r} '
            f'in path {path!r} ({i} layer(s) deep)'
        )
        
        potential_target = os.path.realpath(os.path.join(path, target_fp_obj))
        if os.path.exists(potential_target):
            logger.debug(
                f'Found the {target_fp_obj_name} {target_fp_obj!r} '
                f'in {path!r}'
            )
            return potential_target
        
        # move up one directory
        path = os.path.dirname(path)
        

def search_fp_obj(target_fp_obj, search_paths = [], target_fp_obj_name = DEFAULT_NAME, n_levels = 5):
    
    
    log_error_msg = f'unable to find the {target_fp_obj_name} {target_fp_obj!r} '
    
    # search in `search_paths`, if given
    if search_paths:
        for path in search_paths:
            potential_path = _search_fp_obj_upwards(
                target_fp_obj,
                path,
                target_fp_obj_name,
                n_levels,
                )
            if potential_path is not None:
                return potential_path
        else:
            log_error_msg += (
                f'in any of {search_paths}, moving up to {n_levels} '
                f'levels upawrds, nor '
            )
            
    # check starting at the script full filepath
    script_path = os.path.dirname(sys.argv[0])
    
    potential_path = _search_fp_obj_upwards(
        target_fp_obj,
        script_path,
        target_fp_obj_name,
        n_levels
    )
    if potential_path is not None:
        return potential_path
    else:
        log_error_msg += (
            f'moving up to {n_levels} levels upwards in the folder hierarchy '
            f'from the script path {script_path!r}'
        )
        fnfe = FileNotFoundError(log_error_msg)
        logger.error(fnfe)
        raise fnfe