import importlib
import traceback


replace_list = {
    "dotenv"  : "python-dotenv",
    "sklearn" : "scikit-learn",
    "docx"    : "python-docx",
    "pptx"    : "python-pptx",
    "msoffcrypto": "msoffcrypto-tool",
    "fitz"    : "pymupdf",
    "bs4"     : "beautifulsoup4",
    "OpenGL"  : "PyOpenGL",
    "cv2"     : "opencv-python",
    "PIL"     : "pillow",
    "mp_api"  : "mp-api",
    "win32com": "pywin32",
    }

libraries = {
    "launcher": [
        "wheel", "shutil", "psutil", "pathlib", "tkinter", "tkinter.font", "tkinterdnd2",
       ],
    "base": [
        "fnmatch", "numpy", "scipy", "matplotlib", "mplcursors", "seaborn", 
        "dotenv",
        "chardet", "pygments",
        "tqdm", "toml", 
        "openpyxl", "sklearn", "pandas",
        "ttkthemes", "PyQt6", 
        ],
    "machine-learning": [
        "physbo", "torch", 
        ],
    "science": [
        "pymatgen", "mp_api", "BoltzTraP2", "pydefect",
        ],
    "documents": [
        "docx", "pptx", "msoffcrypto", "pymupdf", "PyPDF2",
        "bs4",
        "jinja2"
        ],
    "converter": [
        "html2text", "markitdown",
        ],
    "multimedia": [
        "PyOpenGL", "cv2", "PIL", 
        "pydub", "pyocr", "pytesseract", "pyperclip", "pyttsx3", " speech_v1p1beta1",
        ],
    "recommended": [
        "monty", "icecream", 
        ],
    "ai": [
        "openai", "google.generativeai", "google.cloud", "whisper",
        ],
    "windows": [
        "winshell", "win32com", "comtypes", 
        ]
    }

print()
print("Checking installed libraries...")
error_list = {}
install_list = {}
for name, libs in libraries.items():
    print(f"{name} libraries:")
    error_list[name] = []
    install_list[name] = []
    for lib in libs:
        try:
            print(f"  checking {lib}...: ", end = '')
            importlib.import_module(lib)
            print(f"  {lib} is installed")
        except OSError as e:
            traceback = traceback.format_exc()
            print(f"  ** Import error {lib}: {e}")
            print(traceback)
            print()
            error_list[name].append(traceback)
        except Exception as e:
            print(f"  ** {lib} is not found: {e}")
            print(f"    Please install by: pip install {replace_list.get(lib, lib)}")
            print()
            install_list[name].append(replace_list.get(lib, lib))

print()
print("Library error summary:")
for name, l in install_list.items():
    if len(l) > 0:
        print(f"  {name}: pip install {' '.join(l)}")
for name, l in error_list.items():
    for message in l:
        print(f"  {name}: {message}")

input("\nPress ENTER to terminate>>\n")

        