# File: cpp_python_debug/core/frozen_utils.py
import sys
import os
import logging
# import tempfile # Non più strettamente necessario per questa logica semplificata
from typing import Optional

logger = logging.getLogger(__name__)

# ... (get_app_base_path come definito correttamente prima) ...
def get_app_base_path() -> str:
    if getattr(sys, "frozen", False):
        application_path = os.path.dirname(sys.executable)
        logger.debug(
            f"get_app_base_path: App is FROZEN. Base path (sys.executable dir): {application_path}"
        )
    else:
        try:
            current_file_abs_path = os.path.abspath(__file__)
            core_dir = os.path.dirname(current_file_abs_path)
            package_root_dir = os.path.dirname(core_dir)
            application_path = os.path.dirname(package_root_dir)
            logger.debug(
                f"get_app_base_path: App is NOT FROZEN. Derived base path (project_root): {application_path}"
            )
        except NameError: 
            application_path = os.getcwd()
            logger.warning(
                f"get_app_base_path: App is NOT FROZEN (__file__ undefined). Using CWD as base path: {application_path}"
            )
    return os.path.normpath(application_path)


def find_resource(relative_path_in_bundle: str) -> Optional[str]:
    """
    Gets the absolute path to a resource, accommodating PyInstaller.
    Gives priority to sys._MEIPASS if defined and frozen.
    """
    logger.debug(f"find_resource: Attempting to find resource with relative_path_in_bundle: '{relative_path_in_bundle}'")
    base_path_to_search: Optional[str] = None

    if getattr(sys, "frozen", False):
        # Applicazione compilata
        if hasattr(sys, "_MEIPASS"):
            # Se _MEIPASS esiste, usalo come base. PyInstaller lo imposta per one-file
            # o a volte anche per one-dir se ci sono hook che scompattano file.
            # Il tuo log mostra che punta a _dist/cpp_python_debug/_internal
            base_path_to_search = sys._MEIPASS
            logger.debug(f"find_resource: App is FROZEN. Using _MEIPASS as base: {base_path_to_search}")
        else:
            # Modalità One-dir standard (nessun _MEIPASS)
            base_path_to_search = os.path.dirname(sys.executable)
            logger.debug(f"find_resource: App is FROZEN (one-dir, no _MEIPASS). Using executable dir as base: {base_path_to_search}")
    else:
        # Modalità Sviluppo
        current_file_dir = os.path.dirname(os.path.abspath(__file__))
        project_root = os.path.abspath(os.path.join(current_file_dir, "..", ".."))
        base_path_to_search = project_root
        logger.debug(f"find_resource: App is NOT FROZEN. Using project root as base: {base_path_to_search}")

    if base_path_to_search is None: # Non dovrebbe accadere
         logger.error("find_resource: base_path_to_search was not determined!")
         return None

    resource_path = os.path.join(base_path_to_search, relative_path_in_bundle)
    normalized_resource_path = os.path.normpath(resource_path)

    logger.debug(f"find_resource: Attempting to locate resource '{relative_path_in_bundle}' at: {normalized_resource_path}")

    if os.path.exists(normalized_resource_path):
        logger.info(f"find_resource: Found resource '{relative_path_in_bundle}': {normalized_resource_path}")
        return normalized_resource_path
    else:
        logger.warning(f"find_resource: Resource '{relative_path_in_bundle}' NOT FOUND at: {normalized_resource_path}")
        # Log aggiuntivo se _MEIPASS era la base usata
        if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS") and base_path_to_search == sys._MEIPASS:
            logger.debug(f"Listing contents of _MEIPASS ('{sys._MEIPASS}'):")
            try:
                for root, _, files in os.walk(sys._MEIPASS): # type: ignore
                    for name in files:
                        logger.debug(f"  - {os.path.join(root, name)}") # type: ignore
            except Exception as e_walk:
                logger.error(f"Could not list _MEIPASS contents: {e_walk}")
        return None