import sys
import os

# ✅ Path to be added in the .pth file
SHARED_LIBS_PATH = "/usr/local/share/shared_libs"
PTH_FILE_NAME = "shared_libs.pth"


def ensure_shared_libs_pth_exists():
    """
    Checks if all site-packages directories have a `.pth` file with the correct path.
    Creates or updates it if missing or incorrect.
    """
    # Search for all site-packages directories (e.g., /usr/lib/python3.x/site-packages/)
    for root, dirs, files in os.walk("/usr"):
        if "site-packages" in dirs:
            site_packages_dir = os.path.join(root, "site-packages")

            pth_file_path = os.path.join(site_packages_dir, PTH_FILE_NAME)

            # Check if the file exists and is correct
            if not os.path.exists(pth_file_path):
                print(f"⚠️ .pth file not found: {pth_file_path}. Creating...")
                with open(pth_file_path, "w") as f:
                    f.write(SHARED_LIBS_PATH + "\n")

            else:
                # Check if the correct path is in the file
                with open(pth_file_path, "r") as f:
                    content = f.read().strip()

                if not content == SHARED_LIBS_PATH:
                    print(f"⚠️ .pth file exists but has incorrect content. Fixing...")
                    with open(pth_file_path, "w") as f:
                        f.write(SHARED_LIBS_PATH + "\n")

    print("✅ All .pth files checked and corrected.")


def main():
    try:
        # Try to import the module
        from shared_libs.wp_app_config import AppConfig

        print("✅ 'shared_libs' is correctly loaded. Starting the application...")

        # Your main program logic here...
    except ModuleNotFoundError as e:
        # Only handle errors related to missing .pth file
        if "No module named 'shared_libs'" in str(e):
            print("⚠️ Error: 'shared_libs' module not found. Checking .pth file...")
            ensure_shared_libs_pth_exists()

            # Try again after fixing the .pth file
            try:
                from shared_libs.wp_app_config import AppConfig

                print("✅ After correcting the .pth file: Module loaded.")
                # Your main program logic here...
            except Exception as e2:
                print(f"❌ Error after correcting the .pth file: {e2}")
        else:
            # For other errors, re-raise them
            raise


if __name__ == "__main__":
    main()