##########################################################
# Install and Test Python Packages                       #
# Data Analytics in Marketing - All Chapter Examples     #
##########################################################

# Run this script once, from top to bottom, before the first class example.
# It installs every package used in the Python chapter examples (only the ones
# you are missing) and then checks that each package loads. The last lines
# print a report. If every package says "OK", Python is set up correctly.
#
# Run it with the same Python you will use for the examples (for example, in
# VS Code, Spyder, or PyCharm). The packages are installed into that Python.
# Installing everything can take several minutes the first time, and you need
# an internet connection.

## Load Packages (these come with Python)
import sys
import subprocess
import importlib

## Step 1: Check your version of Python
## The examples were tested with Python 3.14. Any recent version (3.10 or later) should work.
print("Your Python version:", sys.version.split()[0])
print("Python location:", sys.executable)
if sys.version_info < (3, 10):
    print("WARNING: Your version of Python is older than 3.10. Please install the latest "
          "version of Python from https://www.python.org before continuing.")

## Step 2: List of packages used in the chapter examples
## Each entry is: (name used with import, name used with pip install, chapters)
packages = [
    ("pandas",      "pandas",       "All chapters - data manipulation"),
    ("numpy",       "numpy",        "All chapters - calculations"),
    ("matplotlib",  "matplotlib",   "All chapters - plots and maps"),
    ("scipy",       "scipy",        "Chapters 3, 11, 16, 17 - statistics"),
    ("sklearn",     "scikit-learn", "Chapters 3, 4, 5, 17 - clustering, LDA, PCA"),
    ("statsmodels", "statsmodels",  "Chapters 4, 8, 11, 12, 13, 15, 16, 17 - regression"),
    ("geopandas",   "geopandas",    "Chapters 3, 4 - maps"),
    ("pygris",      "pygris",       "Chapters 3, 4 - zip code and state boundaries"),
    ("adjustText",  "adjustText",   "Chapter 5 - labels on the perceptual maps"),
    ("nltk",        "nltk",         "Chapter 17 - stop words and word stemming"),
    ("tomotopy",    "tomotopy",     "Chapter 17 - topic model"),
    ("wordcloud",   "wordcloud",    "Chapter 17 - word clouds"),
]

## Step 3: Install any packages that are missing
def is_installed(import_name):
    try:
        importlib.import_module(import_name)
        return True
    except ImportError:
        return False

missing = [pip_name for import_name, pip_name, _ in packages if not is_installed(import_name)]
if missing:
    print(f"Installing {len(missing)} package(s): {', '.join(missing)}")
    subprocess.run([sys.executable, "-m", "pip", "install", *missing])
    importlib.invalidate_caches()
else:
    print("All packages are already installed.")

## Step 4: Check that every package loads
results = []
for import_name, pip_name, used_for in packages:
    try:
        module = importlib.import_module(import_name)
        version = getattr(module, "__version__", "")
        results.append((pip_name, version, "OK", used_for))
    except Exception:
        results.append((pip_name, "", f"FAILED - try: pip install {pip_name}", used_for))

## Step 5: Download the English stop words used in Chapter 17
try:
    import nltk
    nltk.download("stopwords", quiet=True)
    from nltk.corpus import stopwords
    stopwords.words("english")
    results.append(("nltk stop words", "", "OK", "Chapter 17 - list of stop words"))
except Exception:
    results.append(("nltk stop words", "", "FAILED - check your internet connection",
                    "Chapter 17 - list of stop words"))

## Step 6: Check the file-choosing dialog box (used in every example to open data files)
try:
    from tkinter import Tk
    root = Tk()
    root.withdraw()
    root.destroy()
    results.append(("tkinter", "", "OK", "All chapters - file-choosing dialog box"))
except Exception:
    results.append(("tkinter", "", "FAILED - reinstall Python from https://www.python.org "
                    "(include Tcl/Tk)", "All chapters - file-choosing dialog box"))

## Step 7: Quick test that plots work (a plot window should appear; close it to continue)
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(range(1, 11), [x ** 2 for x in range(1, 11)], color="steelblue")
ax.set_title("If you can see this plot, plotting works!")
plt.show()

## Step 8: Report
print("\n==================== Package Report ====================")
for name, version, status, used_for in results:
    print(f"{name:<17}{version:<12}{status}")
failed = [name for name, _, status, _ in results if status != "OK"]
if not failed:
    print(f"\nSUCCESS: All {len(results)} checks passed. You are ready to run the chapter examples.")
else:
    print(f"\nPROBLEM: {len(failed)} check(s) failed: {', '.join(failed)}")
    print("Try running this script again. If a package still fails, restart Python "
          "(or your editor) and run the script one more time.")
