"""Check a Squirro RPM node for what the move from Python 3.11 to 3.14 changes.

Read-only. Run it on every cluster node, before the upgrade with
/opt/squirro/virtualenv311/bin/python and after it with
/opt/squirro/virtualenv314/bin/python, as root for a complete report:

    sudo /opt/squirro/virtualenv311/bin/python squirro-py314-check.py [--json]

Exit code: 0 when nothing needs action, 1 when something does, 2 when the
script itself failed, 3 when nothing it could check needs action but some
checks couldn't run (rerun as root, or see what's not checked).
"""

# The syntax stays within Python 3.6, so that run with the system python3 the
# script gets as far as saying which interpreter to use.
import argparse
import ast
import base64
import configparser
import fnmatch
import hashlib
import importlib.util
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import textwrap
import tokenize
import urllib.parse
import warnings
from pathlib import Path
from typing import (
    Any,
    Callable,
    Dict,
    FrozenSet,
    List,
    NamedTuple,
    Optional,
    Sequence,
    Set,
    Tuple,
)

VERSION = "1.5.0"

# The third-party squirro-python314-* packages of the release this checks for, by the
# name after the prefix (Squirro's own packages are always shipped). Regenerate with
# generate_package_list.py, next to this script in the Squirro platform repository.
# BEGIN GENERATED PACKAGES
TARGET_RELEASE = "3.17.4"
PY314_RPMS = {
    "aiohappyeyeballs": "2.6.1",
    "aiohttp": "3.13.3",
    "aiosignal": "1.4.0",
    "amqp": "5.2.0",
    "annotated-doc": "0.0.5",
    "annotated_types": "0.6.0",
    "anyio": "4.14.2",
    "apscheduler": "3.10.4",
    "argon2-cffi": "23.1.0",
    "argon2-cffi-bindings": "21.2.0",
    "asgiref": "3.8.1",
    "astor": "0.8.1",
    "asttokens": "2.2.1",
    "async-timeout": "4.0.3",
    "attrs": "21.4.0",
    "autogluon.common": "1.6.3",
    "autogluon.core": "1.6.3",
    "autogluon.features": "1.6.3",
    "autogluon.tabular": "1.6.3",
    "automat": "22.10.0",
    "azure-core": "1.34.0",
    "azure-identity": "1.23.0",
    "babel": "2.9.1",
    "beautifulsoup4": "4.13.5",
    "bleach": "6.4.0",
    "blinker": "1.8.2",
    "blis": "1.3.2",
    "boto3": "1.34.92",
    "botocore": "1.34.92",
    "cachetools": "4.1.1",
    "camelot-py": "1.0.0",
    "catalogue": "2.0.10",
    "catboost": "1.2.9",
    "certifi": "2026.10.19",
    "cffi": "2.0.0",
    "chardet": "3.0.4",
    "charset-normalizer": "2.0.7",
    "click": "8.1.7",
    "cloudpathlib": "0.23.0",
    "cloudpickle": "3.1.1",
    "colorama": "0.4.6",
    "commonmark": "0.9.1",
    "compressed-rtf": "1.0.6",
    "confection": "1.3.2",
    "constantly": "15.1.0",
    "contourpy": "1.3.3",
    "coverage": "7.6.11",
    "cron-validator": "1.0.3",
    "cryptography": "42.0.5",
    "cssselect": "1.2.0",
    "cssutils": "2.11.0",
    "cycler": "0.11.0",
    "cymem": "2.0.12",
    "cytoolz": "1.1.0",
    "daemon": "3.1.0",
    "databricks-cli": "0.18.0",
    "datasets": "4.8.0",
    "dateparser": "1.2.0",
    "dateutil": "2.8.2",
    "de-core-news-sm": "3.7.0+squirro1",
    "decorator": "4.3.0",
    "defusedxml": "0.7.1",
    "deprecated": "1.2.13",
    "deprecation": "2.1.0",
    "dill": "0.4.1",
    "docker": "7.2.0",
    "docutils": "0.20",
    "dotenv": "1.0.1",
    "dozer": "0.8",
    "elastic-transport": "9.2.0",
    "elasticsearch": "9.2.0",
    "elementpath": "4.4.0",
    "en-core-web-md": "3.7.1+squirro1",
    "en-core-web-sm": "3.7.1+squirro1",
    "entrypoints": "0.4",
    "et-xmlfile": "1.1.0",
    "events": "0.5",
    "executing": "1.2.0",
    "fastapi": "0.115.6",
    "fasttext": "0.9.3+squirro1",
    "faust-cchardet": "2.2.0",
    "feedparser": "6.0.10",
    "feedwerk": "1.1.0",
    "filelock": "3.0.12",
    "flask": "3.0.3",
    "flask-dance": "7.1.0",
    "flatbuffers": "23.5.26",
    "flup-py3": "1.0.4",
    "fonttools": "4.55.3",
    "fpdf2": "2.7.8",
    "frozenlist": "1.5.0",
    "fsspec": "2023.12.2",
    "ftfy": "4.4.3",
    "future": "1.0.0",
    "gitdb": "4.0.11",
    "gitpython": "3.1.43",
    "googleapis-common-protos": "1.67.0",
    "graphviz": "0.20.3",
    "greenlet": "3.2.3",
    "grpcio": "1.75.1",
    "gunicorn": "23.0.0",
    "h11": "0.16.0",
    "hf-xet": "1.2.0",
    "hiredis": "3.3.0",
    "hjson": "3.1.0",
    "html5lib": "1.1",
    "httpcore": "1.0.9",
    "httplib2": "0.20.4",
    "httptools": "0.7.1",
    "httpx": "0.26.0",
    "huggingface-hub": "0.36.1",
    "hyperlink": "21.0.0",
    "icecream": "2.1.3",
    "idna": "2.8",
    "imapclient": "3.0.1",
    "img2pdf": "0.6.3",
    "importlib-metadata": "7.0.0",
    "importlib-resources": "5.10.1",
    "incremental": "22.10.0",
    "iso8601": "2.1.0",
    "isodate": "0.6.1",
    "itemadapter": "0.8.0",
    "itemloaders": "1.1.0",
    "itsdangerous": "2.2.0",
    "jarowinkler": "2.0.0",
    "jdcal": "1.4.1",
    "jellyfish": "0.5.2",
    "jinja2": "3.1.4",
    "jmespath": "0.9.5",
    "joblib": "1.6.0",
    "jsonschema": "3.2.0",
    "kiwisolver": "1.4.9",
    "kombu": "5.3.5",
    "langcodes": "3.5.1",
    "legacy-cgi": "2.6.4",
    "lightgbm": "4.4.0",
    "lit": "18.1.4",
    "lockfile": "0.12.2",
    "lxml": "6.0.1",
    "lxml-html-clean": "0.4.1",
    "magic": "0.4.18",
    "magika": "0.6.1",
    "mako": "1.2.4",
    "mariadb": "1.1.11",
    "markdown": "2.6.11",
    "markdown-it-py": "3.0.0",
    "markupsafe": "3.0.3",
    "matplotlib": "3.10.5",
    "mccabe": "0.3.1",
    "mdurl": "0.1.2",
    "metaphone": "0.6",
    "mini-racer": "0.12.4",
    "mock": "2.0.0",
    "mpmath": "1.3.0",
    "msal": "1.32.3",
    "msal-extensions": "1.3.1",
    "msgpack": "1.1.2",
    "msgpack-numpy": "0.4.7.1",
    "multidict": "6.1.0",
    "multipart": "0.0.19",
    "multiprocess": "0.70.19",
    "murmurhash": "1.0.14",
    "networkx": "3.1",
    "nltk": "3.10.3",
    "nltk-punkt-tab": "20241211",
    "nltk-stopwords": "20240426",
    "ntlm-auth": "1.5.0",
    "ntlm3": "1.0.2",
    "numpy": "2.3.2",
    "oauth2client": "4.1.3",
    "oauthlib": "3.2.2",
    "objgraph": "3.5.0",
    "ocrmypdf": "15.4.3",
    "olefile": "0.47",
    "onnxruntime": "1.24.1",
    "opencv": "4.14.0.94",
    "openpyxl": "3.1.2",
    "opensearch-protobufs": "0.19.0",
    "opensearch-py": "3.1.0",
    "opentelemetry-api": "1.26.0",
    "opentelemetry-exporter-otlp-proto-common": "1.26.0",
    "opentelemetry-exporter-otlp-proto-grpc": "1.26.0",
    "opentelemetry-exporter-otlp-proto-http": "1.26.0",
    "opentelemetry-instrumentation": "0.47b0",
    "opentelemetry-instrumentation-asgi": "0.47b0",
    "opentelemetry-instrumentation-fastapi": "0.47b0",
    "opentelemetry-instrumentation-logging": "0.47b0",
    "opentelemetry-instrumentation-requests": "0.47b0",
    "opentelemetry-instrumentation-sqlalchemy": "0.47b0",
    "opentelemetry-instrumentation-wsgi": "0.47b0",
    "opentelemetry-proto": "1.26.0",
    "opentelemetry-sdk": "1.26.0",
    "opentelemetry-semantic-conventions": "0.47b0",
    "opentelemetry-util-http": "0.47b0",
    "orjson": "3.11.4",
    "packaging": "24.0",
    "pandas": "2.3.3",
    "parsel": "1.9.1",
    "paste": "3.9.0",
    "patchelf": "0.17.2.1",
    "pathspec": "0.12.1",
    "patsy": "0.5.6",
    "pbr": "6.0.0",
    "pdf2image": "1.17.0",
    "pdfminer.six": "20231228",
    "pikepdf": "9.11.0",
    "pillow": "13.0.0+squirro1",
    "pip": "25.2",
    "plotly": "5.21.0",
    "pluggy": "1.5.0",
    "ply": "3.11",
    "portpicker": "1.6.0",
    "praw": "7.7.1",
    "premailer": "3.10.0",
    "preshed": "3.0.11",
    "prometheus-client": "0.20.0",
    "prometheus-flask-exporter": "0.23.0",
    "propcache": "0.2.0",
    "protego": "0.3.1",
    "protobuf": "4.21.12",
    "psutil": "5.9.8",
    "psycopg2-binary": "2.9.11",
    "pyarrow": "23.0.1",
    "pyarrow-hotfix": "0.6",
    "pyasn1": "0.6.0",
    "pyasn1-modules": "0.4.0",
    "pybind11": "2.12.0",
    "pycparser": "2.22",
    "pycryptodome": "3.20.0",
    "pycryptodomex": "3.20.0",
    "pydantic": "2.12.0",
    "pydantic_core": "2.41.1",
    "pydispatcher": "2.0.7",
    "pyflakes": "3.2.0",
    "pygments": "2.17.2",
    "pyjwt": "2.15.0",
    "pymupdf": "1.28.2",
    "pymysql": "1.1.1",
    "pyopenssl": "24.1.0",
    "pyparsing": "3.1.2",
    "pypdf": "5.0.1",
    "pyrsistent": "0.20.0",
    "pysaml2": "7.3.1",
    "pyseto": "1.7.8",
    "pyspnego": "0.10.2",
    "pytextrank": "3.2.4",
    "pytrec-eval-terrier": "0.5.10",
    "pytz": "2024.1",
    "pyyaml": "6.0.3",
    "querystring-parser": "1.2.4",
    "queuelib": "1.6.2",
    "rapidfuzz": "3.14.1",
    "rawapi": "1.14.23",
    "rdflib": "7.0.0",
    "redis": "5.0.4",
    "regex": "2025.7.29",
    "reportlab": "4.2.0",
    "requests": "2.32.5",
    "requests-file": "2.0.0",
    "requests-ntlm": "1.2.0",
    "requests-oauthlib": "2.0.0",
    "rich": "15.0.0",
    "rq": "1.16.1",
    "s3transfer": "0.10.1",
    "sacremoses": "0.0.43",
    "safetensors": "0.5.0",
    "schema": "0.7.7",
    "scikit-learn": "1.7.2",
    "scipy": "1.16.1",
    "scrapy": "2.11.1",
    "scrapyd": "1.4.3",
    "scrapyd-client": "1.2.3",
    "sentence-transformers": "5.7.0",
    "sentencepiece": "0.2.1",
    "service-identity": "24.1.0",
    "setuptools": "80.9.0",
    "sgmllib3k": "1.0.0",
    "shellingham": "1.5.4",
    "simplejson": "3.19.2",
    "six": "1.16.0",
    "slumber": "0.7.1",
    "smart-open": "6.4.0",
    "smartcrop": "0.3.4",
    "smmap": "5.0.1",
    "sniffio": "1.3.1",
    "sortedcontainers": "2.4.0",
    "soupsieve": "2.5",
    "spacy": "3.8.13",
    "spacy-legacy": "3.0.12",
    "spacy-loggers": "1.0.5",
    "sparqlwrapper": "2.0.0",
    "sqlalchemy": "2.0.54",
    "sqlparse": "0.5.0",
    "srsly": "2.5.3",
    "starlette": "0.41.3",
    "statsmodels": "0.14.5",
    "structlog": "24.1.0",
    "sympy": "1.14.0",
    "tabulate": "0.9.0",
    "tarsafe": "0.0.5",
    "tblib": "3.0.0",
    "tenacity": "8.2.3",
    "texttable": "1.7.0",
    "thinc": "8.3.12",
    "threadpoolctl": "3.4.0",
    "thrift": "0.20.0",
    "tldextract": "5.1.2",
    "tokenizers": "0.21.4",
    "toolz": "0.12.1",
    "torch": "2.10.0+cpu",
    "torchvision": "0.25.0+cpu",
    "tqdm": "4.70.1",
    "traits": "7.1.0",
    "transformers": "4.49.0",
    "treelib": "1.6.4",
    "twisted": "22.10.0",
    "typer": "0.27.3",
    "typing-extensions": "4.16.0",
    "typing-inspection": "0.4.4",
    "tzdata": "2024.1",
    "tzlocal": "5.2",
    "uberegg": "0.1.1",
    "ujson": "5.11.0",
    "uncertainties": "3.2.2",
    "unidecode": "1.3.8",
    "update_checker": "0.18.0",
    "uritemplate": "4.1.1",
    "urllib3": "2.4.0",
    "urlobject": "3.0.0",
    "uvicorn": "0.29.0",
    "uvloop": "0.22.1",
    "vaderSentiment": "3.3.2",
    "vine": "5.1.0",
    "virtualenv": "1.0",
    "w3lib": "2.1.2",
    "wasabi": "1.1.2",
    "watchfiles": "1.1.0",
    "wcwidth": "0.2.13",
    "weasel": "1.0.0",
    "webencodings": "0.5.1",
    "webhelpers": "1.3",
    "webob": "1.8.9",
    "websocket-client": "1.8.0",
    "websockets": "12.0",
    "werkzeug": "3.0.3",
    "wheel": "0.43.0",
    "whoosh": "2.7.4",
    "wrapt": "1.14.2",
    "wsgiservice": "1.0.0",
    "xgboost": "2.0.3",
    "xlrd": "2.0.1",
    "xlsxwriter": "3.2.0",
    "xlwt": "1.3.0",
    "xmlschema": "3.3.1",
    "xxhash": "3.6.0",
    "yappi": "1.7.3",
    "yarl": "1.18.0",
    "zipp": "3.18.2",
    "zope.interface": "8.1",
}
PY314_DISTRIBUTION_NAMES = {
    "opencv-python-headless": "opencv",
}
# END GENERATED PACKAGES

TOOL = "squirro-py314-check"
VENV311 = "/opt/squirro/virtualenv311"
VENV314 = "/opt/squirro/virtualenv314"

ACTION_NEEDED = "action_needed"
INFO = "info"
NOT_CHECKED = "not_checked"
NOT_APPLICABLE = "not_applicable"

SEVERITY_LABELS = {
    ACTION_NEEDED: "action needed",
    INFO: "for your information",
    NOT_CHECKED: "not checked",
    NOT_APPLICABLE: "not applicable",
}


def canonical(name: str) -> str:
    """A package name as PEP 503 compares them."""
    return re.sub(r"[-_.]+", "-", name).lower()


def is_squirro_package(name: str) -> bool:
    """Squirro's own packages, which every release ships and the upgrade replaces."""
    name = canonical(name)
    return name.startswith("squirro-") or name == "squirroclient"


def target_provides(distribution: str) -> bool:
    """Whether the release ships `distribution` as a squirro-python314-* package,
    whose names drop a leading "python-"."""
    if is_squirro_package(distribution):
        return True
    shipped = {canonical(name) for name in PY314_RPMS}
    name = canonical(distribution)
    if name in {canonical(other) for other in PY314_DISTRIBUTION_NAMES}:
        return True
    return name in shipped or (
        name.startswith("python-") and name[len("python-") :] in shipped
    )


def major(version: str) -> str:
    return version.split(".", 1)[0]


class CommandResult(NamedTuple):
    returncode: int
    stdout: str
    stderr: str


class Finding(NamedTuple):
    check: str
    severity: str
    location: str
    problem: str
    action: str


class CheckNotRun(Exception):
    """A check couldn't run; problem and action are ours and safe to show."""

    def __init__(
        self,
        problem: str,
        action: str = "Rerun the script; if it keeps happening, check this by hand.",
    ) -> None:
        super().__init__(problem)
        self.problem = problem
        self.action = action


class Report(NamedTuple):
    mode: Optional[str]
    node: Dict[str, Any]
    findings: List[Finding]


def run_command(argv: Sequence[str], input_text: Optional[str] = None) -> CommandResult:
    env = dict(os.environ, LC_ALL="C")
    try:
        proc = subprocess.run(
            list(argv),
            input=input_text if input_text is not None else "",
            capture_output=True,
            env=env,
            timeout=120,
            text=True,
        )
    except FileNotFoundError:
        return CommandResult(127, "", f"{argv[0]} not found")
    except subprocess.TimeoutExpired:
        return CommandResult(124, "", f"{argv[0]} timed out")
    return CommandResult(proc.returncode, proc.stdout, proc.stderr)


class Node:
    """The node being checked. Every path goes through `path()`, every command
    through `run`, so the checks can be pointed at a fake node."""

    def __init__(
        self,
        root: Path = Path("/"),
        run: Callable[..., CommandResult] = run_command,
        is_root: Optional[bool] = None,
    ) -> None:
        self.root = Path(root)
        self.run = run
        self.is_root = os.geteuid() == 0 if is_root is None else is_root

    def path(self, absolute: str) -> Path:
        return self.root / absolute.lstrip("/")

    @property
    def venv311(self) -> Optional[Path]:
        path = self.path(VENV311)
        return path if path.is_dir() else None

    @property
    def venv314(self) -> Optional[Path]:
        path = self.path(VENV314)
        return path if path.is_dir() else None

    @property
    def mode(self) -> Optional[str]:
        if self.venv314 is not None:
            return "after"
        if self.venv311 is not None:
            return "before"
        return None

    @property
    def os_release(self) -> Dict[str, str]:
        values = {}  # type: Dict[str, str]
        try:
            text = self.path("/etc/os-release").read_text()
        except OSError:
            return values
        for line in text.splitlines():
            key, sep, value = line.partition("=")
            if sep:
                values[key.strip()] = value.strip().strip("\"'")
        return values

    @property
    def squirro_version(self) -> Optional[str]:
        result = self.run(["rpm", "-q", "--qf", "%{VERSION}", "squirro-cluster-node"])
        if result.returncode != 0:
            return None
        return result.stdout.strip() or None

    @property
    def roles(self) -> List[str]:
        """ "cluster" and "storage", from the role packages installed on the node."""
        names = ["squirro-cluster-node", "squirro-storage-node"]
        result = self.run(["rpm", "-q", "--qf", "%{NAME}\\n"] + names)
        installed = {line.strip() for line in result.stdout.splitlines()}
        return [name.split("-")[1] for name in names if name in installed]


# --- Scanning Python sources ----------------------------------------------------------

# Standard library modules removed in Python 3.12 and 3.13.
REMOVED_MODULES = frozenset(
    """aifc asynchat asyncore audioop cgi cgitb chunk crypt distutils imghdr imp lib2to3
    mailcap msilib nis nntplib ossaudiodev pipes smtpd sndhdr spwd sunau telnetlib uu
    xdrlib""".split()
)  # type: FrozenSet[str]

# Standard library names removed in Python 3.12, 3.13 and 3.14, with what replaces them.
REMOVED_APIS = {
    # 3.12
    "configparser.SafeConfigParser": "use configparser.ConfigParser",
    "ssl.wrap_socket": "use ssl.SSLContext.wrap_socket",
    "ssl.match_hostname": "hostname checking is built into ssl.SSLContext",
    "ssl.RAND_pseudo_bytes": "use os.urandom or ssl.RAND_bytes",
    "locale.format": "use locale.format_string",
    "importlib.find_loader": "use importlib.util.find_spec",
    "sqlite3.OptimizedUnicode": "use str",
    "sqlite3.enable_shared_cache": "no replacement",
    "io.OpenWrapper": "use open",
    "pkgutil.ImpImporter": "use importlib",
    "pkgutil.ImpLoader": "use importlib",
    "importlib.abc.Finder": "use importlib.abc.MetaPathFinder or importlib.abc.PathEntryFinder",
    "importlib.util.set_package": "set __package__ on the module directly",
    "importlib.util.set_loader": "set __loader__ on the module directly",
    "importlib.util.module_for_loader": "use importlib.abc.Loader.exec_module",
    # 3.13
    "locale.resetlocale": "use locale.setlocale(locale.LC_ALL, '')",
    "typing.io": "import from typing directly",
    "typing.re": "import from typing directly",
    "unittest.findTestCases": "use unittest.TestLoader.loadTestsFromModule",
    "unittest.makeSuite": "use unittest.TestLoader.loadTestsFromTestCase",
    "unittest.getTestCaseNames": "use unittest.TestLoader.getTestCaseNames",
    "configparser.LegacyInterpolation": "use configparser.BasicInterpolation",
    "re.template": "no replacement",
    "re.TEMPLATE": "no replacement",
    "tkinter.tix": "no replacement",
    # 3.14
    "ast.Num": "use ast.Constant",
    "ast.Str": "use ast.Constant",
    "ast.Bytes": "use ast.Constant",
    "ast.NameConstant": "use ast.Constant",
    "ast.Ellipsis": "use ast.Constant",
    "asyncio.AbstractChildWatcher": "no replacement",
    "asyncio.SafeChildWatcher": "no replacement",
    "asyncio.FastChildWatcher": "no replacement",
    "asyncio.MultiLoopChildWatcher": "no replacement",
    "asyncio.ThreadedChildWatcher": "no replacement",
    "asyncio.PidfdChildWatcher": "no replacement",
    "asyncio.get_child_watcher": "no replacement",
    "asyncio.set_child_watcher": "no replacement",
    "pkgutil.find_loader": "use importlib.util.find_spec",
    "pkgutil.get_loader": "use importlib.util.find_spec",
    "pty.master_open": "use pty.openpty",
    "pty.slave_open": "use pty.openpty",
    "sqlite3.version": "use sqlite3.sqlite_version",
    "sqlite3.version_info": "use sqlite3.sqlite_version_info",
    "urllib.parse.Quoter": "use urllib.parse.quote",
    "urllib.request.URLopener": "use urllib.request.urlopen",
    "urllib.request.FancyURLopener": "use urllib.request.urlopen",
    "importlib.abc.ResourceReader": "use importlib.resources.abc.TraversableResources",
    "importlib.abc.Traversable": "use importlib.resources.abc.Traversable",
    "importlib.abc.TraversableResources": "use importlib.resources.abc.TraversableResources",
}  # type: Dict[str, str]

# Removed methods, recognisable by name: unittest.TestCase's old aliases (3.12) when
# called on self, and ConfigParser.readfp (3.12) on any receiver.
REMOVED_TESTCASE_METHODS = {
    "assertEquals": "assertEqual",
    "assertNotEquals": "assertNotEqual",
    "assert_": "assertTrue",
    "failUnless": "assertTrue",
    "failIf": "assertFalse",
    "failUnlessEqual": "assertEqual",
    "failIfEqual": "assertNotEqual",
    "assertAlmostEquals": "assertAlmostEqual",
    "assertNotAlmostEquals": "assertNotAlmostEqual",
    "failUnlessAlmostEqual": "assertAlmostEqual",
    "failIfAlmostEqual": "assertNotAlmostEqual",
    "failUnlessRaises": "assertRaises",
    "assertRegexpMatches": "assertRegex",
    "assertNotRegexpMatches": "assertNotRegex",
    "assertRaisesRegexp": "assertRaisesRegex",
    "assertDictContainsSubset": "compare the dictionaries directly",
}  # type: Dict[str, str]
REMOVED_METHODS = dict(REMOVED_TESTCASE_METHODS, readfp="read_file")

# Removed keyword arguments, all of them replaced by an ssl.SSLContext: 3.12 (the
# key and certificate files) and 3.13 (urlopen's CA files). SMTP.starttls is matched
# by name, since it's called on an instance.
REMOVED_KEYWORDS = {
    "ftplib.FTP_TLS": ("keyfile", "certfile"),
    "imaplib.IMAP4_SSL": ("keyfile", "certfile"),
    "poplib.POP3_SSL": ("keyfile", "certfile"),
    "smtplib.SMTP_SSL": ("keyfile", "certfile"),
    "starttls": ("keyfile", "certfile"),
    "http.client.HTTPSConnection": ("key_file", "cert_file", "check_hostname"),
    "urllib.request.urlopen": ("cafile", "capath", "cadefault"),
}  # type: Dict[str, Tuple[str, ...]]

# Starting these processes uses the platform's default start method, forkserver on
# Linux from 3.14 on. Manager() starts its server process that way too.
PROCESS_STARTERS = frozenset(
    [
        "multiprocessing.Manager",
        "multiprocessing.Pool",
        "multiprocessing.Process",
        "multiprocessing.pool.Pool",
        "multiprocessing.pool.ThreadPool",
        "concurrent.futures.ProcessPoolExecutor",
    ]
)  # type: FrozenSet[str]


class CodeIssue(NamedTuple):
    line: int
    # removed_module, removed_api, removed_keyword, multiprocessing, event_loop, tarfile,
    # pydantic_v1, unparseable, unscannable
    kind: str
    detail: str


# Pydantic 1's API and LangChain's shims of it, which read class annotations the way
# Python 3.14 no longer stores them.
PYDANTIC_V1_MODULES = frozenset(
    ["pydantic.v1", "langchain_core.pydantic_v1", "langchain.pydantic_v1"]
)  # type: FrozenSet[str]


def _pydantic_v1_module(module: str) -> Optional[str]:
    for name in PYDANTIC_V1_MODULES:
        if module == name or module.startswith(name + "."):
            return name
    return None


def read_source(path: Path) -> Tuple[Optional[str], Optional[str]]:
    """(source, None), or (None, why it can't be read as Python source)."""
    try:
        with tokenize.open(str(path)) as handle:
            source = handle.read()
    except PermissionError:
        return None, "can't be read (permission denied)"
    except (OSError, SyntaxError, UnicodeDecodeError) as exc:
        return None, f"can't be read as Python source ({type(exc).__name__})"
    if "\x00" in source:
        return None, "contains NUL bytes, so it isn't Python source"
    return source, None


def _dotted(node: ast.AST) -> Optional[List[str]]:
    parts = []  # type: List[str]
    current = node
    while isinstance(current, ast.Attribute):
        parts.append(current.attr)
        current = current.value
    if isinstance(current, ast.Name):
        parts.append(current.id)
        return list(reversed(parts))
    return None


class _Scanner(ast.NodeVisitor):
    def __init__(self) -> None:
        self.aliases = {}  # type: Dict[str, str]
        self.issues = []  # type: List[CodeIssue]
        self.process_start_line = 0
        self.explicit_start_method = False
        self.in_coroutine = [False]
        self.pydantic_v1 = None  # type: Optional[Tuple[int, str]]
        self.future_annotations = False
        self.v1_models = set()  # type: Set[str]
        self.v1_model_fields = False
        self.tar_names = set()  # type: Set[str]

    def _opens_tar(self, node: ast.AST) -> bool:
        return isinstance(node, ast.Call) and (
            self._resolve(node.func) or ""
        ).startswith("tarfile.")

    def _is_tar(self, node: ast.AST) -> bool:
        return self._opens_tar(node) or (
            isinstance(node, ast.Name) and node.id in self.tar_names
        )

    def visit_Assign(self, node: ast.Assign) -> None:
        if self._opens_tar(node.value):
            self.tar_names.update(t.id for t in node.targets if isinstance(t, ast.Name))
        self.generic_visit(node)

    def visit_With(self, node: ast.With) -> None:
        for item in node.items:
            if self._opens_tar(item.context_expr) and isinstance(
                item.optional_vars, ast.Name
            ):
                self.tar_names.add(item.optional_vars.id)
        self.generic_visit(node)

    def _note_pydantic_v1(self, line: int, module: str) -> None:
        if self.pydantic_v1 is None:
            self.pydantic_v1 = (line, module)

    def _pydantic_v1_base(self, base: ast.AST) -> bool:
        if isinstance(base, ast.Name) and base.id in self.v1_models:
            return True
        full = self._resolve(base)
        return full is not None and _pydantic_v1_module(full) is not None

    def visit_ClassDef(self, node: ast.ClassDef) -> None:
        if any(self._pydantic_v1_base(base) for base in node.bases):
            self.v1_models.add(node.name)
            if any(isinstance(statement, ast.AnnAssign) for statement in node.body):
                self.v1_model_fields = True
        self.generic_visit(node)

    def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
        self.in_coroutine.append(True)
        self.generic_visit(node)
        self.in_coroutine.pop()

    def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
        self.in_coroutine.append(False)
        self.generic_visit(node)
        self.in_coroutine.pop()

    def visit_Import(self, node: ast.Import) -> None:
        for alias in node.names:
            top = alias.name.split(".")[0]
            if top in REMOVED_MODULES:
                self.issues.append(CodeIssue(node.lineno, "removed_module", top))
            v1 = _pydantic_v1_module(alias.name)
            if v1:
                self._note_pydantic_v1(node.lineno, v1)
            if alias.asname:
                self.aliases[alias.asname] = alias.name
            else:
                self.aliases[top] = top
        self.generic_visit(node)

    def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
        if node.level == 0 and node.module:
            top = node.module.split(".")[0]
            if top in REMOVED_MODULES:
                self.issues.append(CodeIssue(node.lineno, "removed_module", top))
            if node.module == "__future__" and any(
                alias.name == "annotations" for alias in node.names
            ):
                self.future_annotations = True
            v1 = _pydantic_v1_module(node.module)
            if v1 is None and node.module == "pydantic":
                if any(alias.name == "v1" for alias in node.names):
                    v1 = "pydantic.v1"
            if v1:
                self._note_pydantic_v1(node.lineno, v1)
            for alias in node.names:
                full = f"{node.module}.{alias.name}"
                self._check_name(full, node.lineno)
                self.aliases[alias.asname or alias.name] = full
        self.generic_visit(node)

    def _resolve(self, node: ast.AST) -> Optional[str]:
        parts = _dotted(node)
        if not parts or parts[0] not in self.aliases:
            return None
        return ".".join([self.aliases[parts[0]]] + parts[1:])

    def _check_name(self, full: str, line: int) -> bool:
        parts = full.split(".")
        for end in range(len(parts), 1, -1):
            candidate = ".".join(parts[:end])
            if candidate in REMOVED_APIS:
                self.issues.append(CodeIssue(line, "removed_api", candidate))
                return True
        if full in PROCESS_STARTERS and not self.process_start_line:
            self.process_start_line = line
        return False

    def visit_Attribute(self, node: ast.Attribute) -> None:
        full = self._resolve(node)
        if full is not None and self._check_name(full, node.lineno):
            return
        self.generic_visit(node)

    def visit_Name(self, node: ast.Name) -> None:
        full = self.aliases.get(node.id)
        if (
            full is not None
            and full in PROCESS_STARTERS
            and not self.process_start_line
        ):
            self.process_start_line = node.lineno

    def visit_Call(self, node: ast.Call) -> None:
        func = node.func
        full = self._resolve(func)
        if full is None and isinstance(func, ast.Attribute) and func.attr == "starttls":
            full = "starttls"
        for keyword in node.keywords:
            if keyword.arg in REMOVED_KEYWORDS.get(full or "", ()):
                self.issues.append(
                    CodeIssue(
                        node.lineno,
                        "removed_keyword",
                        f"{keyword.arg} argument of {full}()",
                    )
                )
        if full == "asyncio.get_event_loop" and not self.in_coroutine[-1]:
            self.issues.append(CodeIssue(node.lineno, "event_loop", ""))
        if isinstance(func, ast.Attribute):
            if func.attr in REMOVED_METHODS and (
                func.attr not in REMOVED_TESTCASE_METHODS
                or (isinstance(func.value, ast.Name) and func.value.id == "self")
            ):
                self.issues.append(CodeIssue(node.lineno, "removed_api", func.attr))
            if func.attr == "set_start_method" or (
                func.attr == "get_context" and node.args
            ):
                self.explicit_start_method = True
            if (
                func.attr in ("extract", "extractall")
                and self._is_tar(func.value)
                and not any(keyword.arg == "filter" for keyword in node.keywords)
            ):
                self.issues.append(CodeIssue(node.lineno, "tarfile", func.attr))
        if any(keyword.arg == "mp_context" for keyword in node.keywords):
            self.explicit_start_method = True
        self.generic_visit(node)


def parse_source(source: str) -> ast.Module:
    # Parsing warns about invalid escape sequences, on stderr and without the file name.
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        return ast.parse(source)


def scan_source(source: str) -> List[CodeIssue]:
    try:
        tree = parse_source(source)
    except (RecursionError, MemoryError):
        return [CodeIssue(1, "unscannable", "is nested too deeply to be scanned")]
    except (SyntaxError, ValueError) as exc:
        line = getattr(exc, "lineno", None) or 1
        return [
            CodeIssue(
                line,
                "unparseable",
                f"doesn't parse as Python {sys.version_info[0]}.{sys.version_info[1]}",
            )
        ]
    scanner = _Scanner()
    try:
        scanner.visit(tree)
    except (RecursionError, MemoryError):
        return [CodeIssue(1, "unscannable", "is nested too deeply to be scanned")]
    issues = scanner.issues
    if scanner.process_start_line and not scanner.explicit_start_method:
        issues.append(CodeIssue(scanner.process_start_line, "multiprocessing", ""))
    if (
        scanner.pydantic_v1
        and scanner.v1_model_fields
        and not scanner.future_annotations
    ):
        line, module = scanner.pydantic_v1
        issues.append(CodeIssue(line, "pydantic_v1", module))
    return sorted(issues)


def import_lines(source: str) -> Dict[str, int]:
    """Absolute imports' top-level names, each with the first line importing it."""
    try:
        tree = parse_source(source)
    except (SyntaxError, ValueError, RecursionError, MemoryError):
        return {}
    lines = {}  # type: Dict[str, int]
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            names = [alias.name.split(".")[0] for alias in node.names]
        elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
            names = [node.module.split(".")[0]]
        else:
            continue
        for name in names:
            lines[name] = min(lines.get(name, node.lineno), node.lineno)
    return lines


def top_level_imports(source: str) -> Set[str]:
    return set(import_lines(source))


# --- Custom assets ----------------------------------------------------------------------

# Where custom assets live: plugins as <dir>/<tenant>/<name>/, pipelets as
# <dir>/<tenant>/<name>.py (or a directory).
ASSET_KINDS = {
    "pipelet": "/var/lib/squirro/plumber",
    "dataloader_plugin": "/var/lib/squirro/topic/assets/dataloader_plugin",
    "studio_plugin": "/var/lib/squirro/topic/assets/studio_plugin",
    "ml_workflow_plugin": "/var/lib/squirro/topic/assets/ml_workflow_plugin",
    "genai_plugin": "/var/lib/squirro/topic/assets/genai_plugin",
}  # type: Dict[str, str]
# Plugins the GenAI container mounts from the host, without tenants.
GENAI_HOST_PLUGINS = "/var/lib/squirro/genai/plugins"
# The copies Squirro ships; an asset whose code is identical to them isn't custom.
PACKAGED_DIRS = (
    "/opt/squirro/packaged_pipelet_plugins",
    "/opt/squirro/packaged_dataloader_plugins",
    "/opt/squirro/packaged_studio_plugins",
    "/opt/squirro/packaged_ml_workflow_plugins",
)

# Where to go instead of a removed module.
MODULE_HINTS = {
    "imp": "importlib",
    "distutils": "setuptools, sysconfig or shutil",
    "asyncore": "asyncio",
    "asynchat": "asyncio",
    "smtpd": "the aiosmtpd package",
    "telnetlib": "the telnetlib3 package or a plain socket",
    "pipes": "shlex.quote",
    "crypt": "hashlib or the passlib package",
    "imghdr": "the filetype package or Pillow",
    "sndhdr": "the filetype package",
    "uu": "base64",
    "cgi": "the email and urllib.parse modules",
    "cgitb": "the traceback module",
    "lib2to3": "the ast module",
}  # type: Dict[str, str]

# Removed modules that a package the release ships puts back.
MODULE_REPLACEMENTS = {"cgi": "legacy-cgi", "cgitb": "legacy-cgi"}  # type: Dict[str, str]

# Overridden in tests; the interpreter the script runs in.
RUNNING_PREFIX = sys.prefix

SUDO_HINT = "Rerun the script with sudo, so it can read everything."


def path_kind(path: Path) -> Optional[str]:
    """ "dir", "file", "other", or None when it doesn't exist. Raises PermissionError when
    it can't be told: Path.is_dir() swallows that on Python 3.14, which would make an
    unreadable folder look absent."""
    try:
        mode = path.stat().st_mode
    except (FileNotFoundError, NotADirectoryError):
        return None
    if stat.S_ISDIR(mode):
        return "dir"
    return "file" if stat.S_ISREG(mode) else "other"


class Asset(NamedTuple):
    kind: str
    tenant: str
    name: str
    path: Path
    genai: bool

    @property
    def label(self) -> str:
        return "{} {}".format(
            self.kind,
            f"{self.tenant}/{self.name}" if self.tenant else self.name,
        )

    def python_files(self, unreadable: Optional[List[str]] = None) -> List[Path]:
        if self.path.suffix == ".py":
            return [self.path]
        files = []  # type: List[Path]

        def failed(error: OSError) -> None:
            if unreadable is not None:
                unreadable.append(str(error.filename))

        for dirpath, dirnames, filenames in os.walk(str(self.path), onerror=failed):
            # pkg/ holds the asset's installed dependencies: PY314-DEPS looks at it.
            dirnames[:] = sorted(d for d in dirnames if d not in ("pkg", "__pycache__"))
            files.extend(
                Path(dirpath, name)
                for name in sorted(filenames)
                if name.endswith(".py")
            )
        return files


def not_checked(
    check: str, location: str, problem: str, action: str = SUDO_HINT
) -> Finding:
    return Finding(check, NOT_CHECKED, location, problem, action)


def _sha256(path: Path) -> Optional[str]:
    try:
        return hashlib.sha256(path.read_bytes()).hexdigest()
    except OSError:
        return None


def shipped_hashes(node: Node) -> Set[str]:
    hashes = set()  # type: Set[str]
    for directory in PACKAGED_DIRS:
        for dirpath, _, filenames in os.walk(str(node.path(directory))):
            for name in filenames:
                if name.endswith(".py"):
                    digest = _sha256(Path(dirpath, name))
                    if digest:
                        hashes.add(digest)
    return hashes


def _listdir(
    path: Path, check: str, location: str, problems: List[Finding]
) -> List[Path]:
    try:
        return sorted(path.iterdir())
    except PermissionError:
        problems.append(
            not_checked(
                check, location, "Couldn't list this directory (permission denied)."
            )
        )
    except OSError:
        pass
    return []


def _kind_or_report(
    node: Node, path: Path, check: str, problems: List[Finding]
) -> Optional[str]:
    try:
        return path_kind(path)
    except PermissionError:
        shown = "/" + str(path.relative_to(node.root))
        problems.append(
            not_checked(check, shown, "Couldn't read it (permission denied).")
        )
        return None


def find_assets(node: Node, check: str) -> Tuple[List[Asset], List[Finding]]:
    """Every asset on the node, shipped or custom, and what couldn't be read."""
    assets = []  # type: List[Asset]
    problems = []  # type: List[Finding]
    for kind, directory in ASSET_KINDS.items():
        for tenant_dir in _listdir(node.path(directory), check, directory, problems):
            if _kind_or_report(node, tenant_dir, check, problems) != "dir":
                continue
            listing = f"{directory}/{tenant_dir.name}"
            for entry in _listdir(tenant_dir, check, listing, problems):
                entry_kind = _kind_or_report(node, entry, check, problems)
                if entry_kind == "dir" or (
                    entry_kind == "file" and entry.name.endswith(".py")
                ):
                    assets.append(
                        Asset(
                            kind,
                            tenant_dir.name,
                            entry.name,
                            entry,
                            kind == "genai_plugin",
                        )
                    )
    for entry in _listdir(
        node.path(GENAI_HOST_PLUGINS), check, GENAI_HOST_PLUGINS, problems
    ):
        entry_kind = _kind_or_report(node, entry, check, problems)
        if entry_kind == "dir" or (entry_kind == "file" and entry.name.endswith(".py")):
            assets.append(Asset("genai_plugin", "", entry.name, entry, True))
    return assets, problems


def find_custom_assets(
    node: Node, check: str = "PY314-ASSETS"
) -> Tuple[List[Asset], List[Finding]]:
    """The assets whose code isn't byte for byte what Squirro ships."""
    assets, problems = find_assets(node, check)
    shipped = shipped_hashes(node)
    custom = []  # type: List[Asset]
    for asset in assets:
        unreadable = []  # type: List[str]
        files = asset.python_files(unreadable)
        # An asset that can't be read is kept, so that check_assets reports it.
        if unreadable or (
            files and not all(_sha256(path) in shipped for path in files)
        ):
            custom.append(asset)
    return custom, problems


def _module_names(folder: Path) -> Set[str]:
    names = set()  # type: Set[str]
    try:
        for entry in folder.iterdir():
            names.add(entry.name.split(".", 1)[0])
    except OSError:
        pass
    return names


def _local_names(asset: Asset) -> Set[str]:
    """What the asset itself provides: its own modules, in subfolders too (plugins put
    those on the import path themselves), and the dependencies installed into its pkg/
    folder, which are on the import path when it runs."""
    folder = asset.path.parent if asset.path.suffix == ".py" else asset.path
    names = _module_names(folder)
    if asset.path.is_dir():
        for dirpath, dirnames, filenames in os.walk(str(folder)):
            dirnames[:] = sorted(
                d
                for d in dirnames
                if not d.startswith(".")
                and d != "__pycache__"
                and not (d == "pkg" and dirpath == str(folder))
            )
            names.update(d for d in dirnames)
            names.update(f[:-3] for f in filenames if f.endswith(".py"))
    pkg = folder / "pkg"
    names |= _module_names(pkg)
    for dirpath, dirnames, _ in os.walk(str(pkg)):
        dirnames[:] = sorted(dirnames)
        if dirpath.endswith("site-packages"):
            names |= _module_names(Path(dirpath))
    return names


def _stdlib_names() -> FrozenSet[str]:
    return frozenset(getattr(sys, "stdlib_module_names", ()))


def venv_import_names(venv: Path) -> Set[str]:
    """The top-level names a virtualenv's site-packages provide."""
    names = set()  # type: Set[str]
    for site in sorted(venv.glob("lib*/python3.*/site-packages")):
        names |= _module_names(site)
    return names


def _missing_imports(
    mode: str,
    names: Set[str],
    local: Set[str],
    package_map: Optional[Dict[str, List[str]]],
    resolved_before: Optional[Set[str]] = None,
) -> List[Tuple[str, str]]:
    """(import name, where it came from) for third-party imports that won't be there.
    After the upgrade, with `resolved_before` (what virtualenv311 provides), only the
    imports the upgrade broke: one that virtualenv311 lacked didn't work before either."""
    stdlib = _stdlib_names()
    candidates = sorted(
        name
        for name in names
        if name not in stdlib and name not in local and not name.startswith("squirro")
    )
    missing = []  # type: List[Tuple[str, str]]
    if mode == "before":
        for name in candidates:
            distributions = (package_map or {}).get(name)
            if distributions and not any(target_provides(d) for d in distributions):
                missing.append((name, ", ".join(sorted(set(distributions)))))
    else:
        for name in candidates:
            if resolved_before is not None and name not in resolved_before:
                continue
            try:
                spec = importlib.util.find_spec(name)
            except (
                ImportError,
                ValueError,
            ):  # a broken package still counts as present
                continue
            if spec is None:
                missing.append((name, ""))
    return missing


def _issue_finding(asset: Asset, relative: str, issue: CodeIssue) -> Finding:
    location = f"{asset.label}, {relative}:{issue.line}"
    detail = issue.detail
    if issue.kind == "unscannable":
        return not_checked(
            "PY314-ASSETS",
            f"{asset.label}, {relative}",
            f"This file {detail}.",
            "Check it by hand.",
        )
    if issue.kind == "removed_module":
        replacement = MODULE_REPLACEMENTS.get(detail)
        if replacement and not asset.genai and target_provides(replacement):
            return Finding(
                "PY314-ASSETS",
                INFO,
                location,
                f"Imports {detail}, which Python removed after 3.11; it keeps working through the {replacement} package "
                "Squirro ships.",
                f"Nothing needed now; moving off {detail} avoids depending on {replacement}.",
            )
        return Finding(
            "PY314-ASSETS",
            ACTION_NEEDED,
            location,
            f"Imports {detail}, which Python removed after 3.11, so this fails on Python 3.14.",
            "Replace it with {}.".format(
                MODULE_HINTS.get(detail, "a maintained package or module")
            ),
        )
    if issue.kind == "removed_api":
        hint = REMOVED_APIS.get(detail) or "use {}".format(
            REMOVED_METHODS.get(detail, "its replacement")
        )
        return Finding(
            "PY314-ASSETS",
            ACTION_NEEDED,
            location,
            f"Uses {detail}, which Python removed after 3.11, so this fails on Python 3.14.",
            hint[0].upper() + hint[1:] + ".",
        )
    if issue.kind == "removed_keyword":
        return Finding(
            "PY314-ASSETS",
            ACTION_NEEDED,
            location,
            f"Passes the {detail}, which Python removed after 3.11, so this fails on Python 3.14.",
            "Pass an ssl.SSLContext instead, set up with load_cert_chain() or "
            "load_verify_locations().",
        )
    if issue.kind == "event_loop":
        return Finding(
            "PY314-ASSETS",
            INFO,
            location,
            "Calls asyncio.get_event_loop() outside a coroutine. On Python 3.14 it raises "
            "RuntimeError when no event loop is set, instead of creating one.",
            "Run coroutines with asyncio.run(), or create the loop with "
            "asyncio.new_event_loop() and asyncio.set_event_loop().",
        )
    if issue.kind == "multiprocessing":
        return Finding(
            "PY314-ASSETS",
            INFO,
            location,
            "Starts processes without choosing a start method. On Python 3.14, Linux uses forkserver: "
            "whatever is passed to a new process must be picklable, and it doesn't inherit the "
            "parent's module state.",
            "Check that it still works, or choose the start method explicitly with "
            "multiprocessing.get_context().",
        )
    if issue.kind == "pydantic_v1":
        return Finding(
            "PY314-ASSETS",
            ACTION_NEEDED,
            location,
            f"Defines models with Pydantic 1 ({detail}). Python 3.14 evaluates class annotations lazily, so "
            "Pydantic 1 finds no fields: the models accept any input, and LangChain tools built on them "
            "lose their arguments. Nothing raises an error.",
            "Add from __future__ import annotations at the top of this file, or move the models to "
            "Pydantic 2.",
        )
    if issue.kind == "tarfile":
        return Finding(
            "PY314-ASSETS",
            INFO,
            location,
            f"Calls {detail}() on a tar archive without a filter. Python 3.14 applies the 'data' filter by "
            "default, which refuses absolute paths, links that leave the target directory and special "
            "files.",
            "Pass filter='data' explicitly, or another filter if the archive needs it.",
        )
    return Finding(
        "PY314-ASSETS",
        INFO,
        location,
        f"{detail[0].upper() + detail[1:]}, so it can't be loaded today either (Python 2 code, "
        "for example); the upgrade doesn't change that.",
        "Remove it if it's no longer used, or port it to Python 3.",
    )


def check_assets(node: Node) -> List[Finding]:
    mode = node.mode or "before"
    venv = node.venv314 if mode == "after" else node.venv311
    assets, findings = find_custom_assets(node)
    imports_checked = (
        venv is not None and Path(RUNNING_PREFIX).resolve() == venv.resolve()
    )
    if assets and not imports_checked and any(not asset.genai for asset in assets):
        findings.append(
            not_checked(
                "PY314-ASSETS",
                "third-party imports",
                "The script doesn't run in the node's {} virtualenv, so it can't tell which packages "
                "will be there.".format("3.14" if mode == "after" else "3.11"),
                "Run it with {}/bin/python.".format(
                    VENV314 if mode == "after" else VENV311
                ),
            )
        )
    package_map = None  # type: Optional[Dict[str, List[str]]]
    if (
        mode == "before"
        and imports_checked
        and any(not asset.genai for asset in assets)
    ):
        from importlib import metadata

        package_map = metadata.packages_distributions()
    resolved_before = (
        venv_import_names(node.venv311)
        if mode == "after" and node.venv311 is not None
        else None
    )
    for asset in assets:
        base = asset.path.parent if asset.path.suffix == ".py" else asset.path
        local = _local_names(asset)
        unreadable = []  # type: List[str]
        files = asset.python_files(unreadable)
        if unreadable:
            findings.append(
                not_checked(
                    "PY314-ASSETS",
                    asset.label,
                    f"Couldn't read {len(unreadable)} of its folder(s) (permission denied).",
                )
            )
        for path in files:
            relative = str(path.relative_to(base))
            source, reason = read_source(path)
            if source is None:
                findings.append(
                    not_checked(
                        "PY314-ASSETS",
                        f"{asset.label}, {relative}",
                        f"This file {reason}.",
                        SUDO_HINT
                        if "permission" in (reason or "")
                        else "Check the file by hand.",
                    )
                )
                continue
            findings.extend(
                _issue_finding(asset, relative, issue) for issue in scan_source(source)
            )
            if asset.genai or not imports_checked:
                continue
            lines = import_lines(source)
            for name, origin in _missing_imports(
                mode, set(lines), local, package_map, resolved_before
            ):
                where = f" ({origin})" if origin else ""
                findings.append(
                    Finding(
                        "PY314-ASSETS",
                        ACTION_NEEDED,
                        f"{asset.label}, {relative}:{lines[name]}",
                        "Imports {}{}, which {}.".format(
                            name,
                            where,
                            "isn't installed in virtualenv314"
                            if mode == "after"
                            else "the Python 3.14 release doesn't ship",
                        ),
                        f"Install it into {VENV314} after the upgrade, add it to the asset's requirements.txt, "
                        "or remove the dependency.",
                    )
                )
    return findings


# --- Plugin dependencies ----------------------------------------------------------------

EXTENSION = re.compile(r"\.cpython-(\d)(\d+)[a-z]*-[^/]*\.so$")


def _metadata_name_version(info: Path) -> Tuple[str, str]:
    name, version = info.name.rsplit(".", 1)[0], ""
    if "-" in name:
        name, version = name.split("-", 1)
    try:
        for line in (info / "METADATA").read_text(errors="replace").splitlines():
            if line.startswith("Name:"):
                name = line[5:].strip()
            elif line.startswith("Version:"):
                version = line[8:].strip()
            elif not line.strip():
                break
    except OSError:
        pass
    return name, version


def venv_distributions(venv: Path) -> Dict[str, Tuple[str, str]]:
    """canonical name -> (name, version) of what's installed in a virtualenv, read
    from its .dist-info folders without importing anything."""
    found = {}  # type: Dict[str, Tuple[str, str]]
    for site in sorted(venv.glob("lib*/python3.*/site-packages")):
        for info in sorted(site.glob("*.dist-info")):
            name, version = _metadata_name_version(info)
            found[canonical(name)] = (name, version)
    return found


def _site_dirs(pkg: Path, unreadable: List[str]) -> List[Path]:
    sites = [pkg]
    for dirpath, dirnames, _ in os.walk(
        str(pkg), onerror=lambda e: unreadable.append(e.filename)
    ):
        dirnames[:] = sorted(dirnames)
        if os.path.basename(dirpath) == "site-packages":
            sites.append(Path(dirpath))
    return sites


def _distribution_files(site: Path, info: Path, unreadable: List[str]) -> List[Path]:
    tops = []  # type: List[str]
    try:
        tops = (info / "top_level.txt").read_text().split()
    except OSError:
        try:
            for line in (info / "RECORD").read_text().splitlines():
                first = line.split(",", 1)[0].split("/", 1)[0]
                if (
                    first
                    and first != ".."
                    and not first.endswith((".dist-info", ".egg-info"))
                ):
                    tops.append(
                        first.rsplit(".py", 1)[0] if first.endswith(".py") else first
                    )
        except OSError:
            pass
    files = []  # type: List[Path]
    for top in sorted(set(tops)):
        package = site / top
        if package.is_dir():
            for dirpath, dirnames, filenames in os.walk(
                str(package), onerror=lambda e: unreadable.append(e.filename)
            ):
                dirnames[:] = sorted(dirnames)
                files.extend(Path(dirpath, name) for name in sorted(filenames))
        if (site / (top + ".py")).is_file():
            files.append(site / (top + ".py"))
        files.extend(sorted(site.glob(top + ".cpython-*.so")))
    return files


def _dependency_problems(files: List[Path], genai: bool) -> List[str]:
    """What keeps a plugin's private dependency from working on Python 3.14. A removed
    module the release brings back as a package (cgi through legacy-cgi) still imports,
    except in the GenAI container, whose packages aren't the virtualenv's."""
    problems = []  # type: List[str]
    versions = set()  # type: Set[str]
    removed = set()  # type: Set[str]
    for path in files:
        match = EXTENSION.search(path.name)
        if match and (match.group(1), match.group(2)) != ("3", "14"):
            versions.add(f"{match.group(1)}.{match.group(2)}")
        elif path.suffix == ".py":
            source, _ = read_source(path)
            if source:
                removed.update(
                    i.detail
                    for i in scan_source(source)
                    if i.kind == "removed_module"
                    and (
                        genai
                        or not target_provides(MODULE_REPLACEMENTS.get(i.detail, ""))
                    )
                )
    if versions:
        problems.append(
            "Compiled for Python {}, which Python 3.14 can't load.".format(
                ", ".join(sorted(versions))
            )
        )
    if removed:
        problems.append(
            "Imports {}, which Python removed after 3.11.".format(
                ", ".join(sorted(removed))
            )
        )
    return problems


def check_deps(node: Node) -> List[Finding]:
    mode = node.mode or "before"
    assets, findings = find_assets(node, "PY314-DEPS")
    installed = (
        venv_distributions(node.venv314) if mode == "after" and node.venv314 else {}
    )

    def provided(name: str) -> bool:
        if mode == "after":
            return canonical(name) in installed or is_squirro_package(name)
        return target_provides(name)

    for asset in assets:
        pkg = asset.path / "pkg"
        if _kind_or_report(node, pkg, "PY314-DEPS", findings) != "dir":
            continue
        unreadable_pkg = []  # type: List[str]
        for site in _site_dirs(pkg, unreadable_pkg):
            for info in sorted(site.glob("*.dist-info")) + sorted(
                site.glob("*.egg-info")
            ):
                name, version = _metadata_name_version(info)
                # A GenAI plugin's pkg/ holds all its requirements (installed with
                # --ignore-installed) and runs in the GenAI container, so what the
                # platform's virtualenv provides says nothing about it.
                if not asset.genai and provided(name):
                    continue
                problems = _dependency_problems(
                    _distribution_files(site, info, unreadable_pkg), asset.genai
                )
                if problems:
                    findings.append(
                        Finding(
                            "PY314-DEPS",
                            ACTION_NEEDED if mode == "after" else INFO,
                            f"{asset.label}, pkg: {name} {version}".rstrip(),
                            " ".join(problems),
                            "Upload the plugin again{}, so its dependencies are installed for "
                            "Python 3.14.".format(
                                "" if mode == "after" else " after the upgrade"
                            ),
                        )
                    )
        if unreadable_pkg:
            findings.append(
                not_checked(
                    "PY314-DEPS",
                    f"{asset.label}, pkg/",
                    f"Couldn't read {len(unreadable_pkg)} folder(s) in its pkg/ folder (permission denied).",
                )
            )
    return findings


# --- Python packages ---------------------------------------------------------------------

# What virtualenv itself installs; never counted as installed by hand.
VENV_TOOLS = frozenset(["pip", "setuptools", "wheel"])  # type: FrozenSet[str]


def installed_rpms(node: Node, prefix: str) -> Dict[str, str]:
    """Installed packages whose name starts with `prefix`: name after it -> version."""
    result = node.run(["rpm", "-qa", "--qf", "%{NAME} %{VERSION}\\n", prefix + "*"])
    if result.returncode != 0:
        raise CheckNotRun(
            "Couldn't list the installed packages with rpm.",
            "Check that the rpm command works on this node, then rerun the script.",
        )
    packages = {}  # type: Dict[str, str]
    for line in result.stdout.splitlines():
        fields = line.split()
        if len(fields) == 2 and fields[0].startswith(prefix):
            packages[fields[0][len(prefix) :]] = fields[1]
    return packages


def _packaged(distribution: str, rpm_names: Set[str]) -> bool:
    name = canonical(distribution)
    return name in rpm_names or (
        name.startswith("python-") and name[len("python-") :] in rpm_names
    )


def rpm_wheel_distributions(node: Node) -> Set[str]:
    """The distributions whose wheels the installed squirro-python311-* packages own:
    they're installed from those wheels, whatever the package is called."""
    result = node.run(
        ["rpm", "-qa", "--qf", "[%{FILENAMES}\\n]", "squirro-python311-*"]
    )
    if result.returncode != 0:
        return set()
    return {
        canonical(os.path.basename(line).split("-", 1)[0])
        for line in result.stdout.splitlines()
        if line.endswith(".whl")
    }


def check_pip(node: Node) -> List[Finding]:
    if node.venv311 is None:
        return []
    rpm_names = {canonical(name) for name in installed_rpms(node, "squirro-python311-")}
    rpm_names |= rpm_wheel_distributions(node)
    by_hand = [
        (name, version)
        for key, (name, version) in sorted(venv_distributions(node.venv311).items())
        if key not in VENV_TOOLS
        and not is_squirro_package(name)
        and not _packaged(name, rpm_names)
    ]
    if node.mode == "after":
        installed = venv_distributions(node.venv314) if node.venv314 else {}
        missing = [(n, v) for n, v in by_hand if canonical(n) not in installed]
        problem = (
            "Installed by hand into virtualenv311, but missing from virtualenv314."
        )
    else:
        missing = [(n, v) for n, v in by_hand if not target_provides(n)]
        problem = (
            "Installed by hand into virtualenv311, and the Python 3.14 release doesn't ship it, "
            "so it won't be in virtualenv314."
        )
    return [
        Finding(
            "PY314-PIP",
            ACTION_NEEDED,
            f"{name} {version}",
            problem,
            "{}nstall it into virtualenv314 (sudo {}/bin/pip install '{}'), in a version that "
            "works on Python 3.14.".format(
                "I" if node.mode == "after" else "After the upgrade, i", VENV314, name
            ),
        )
        for name, version in missing
    ]


def _dated(version: str) -> bool:
    """A version that starts with a year (certifi, regex): its first part isn't a major."""
    first = major(version)
    return first.isdigit() and int(first) >= 1990


def _packages(count: int) -> str:
    return f"{count} squirro-python311-* package{'' if count == 1 else 's'}"


def check_rpms(node: Node) -> List[Finding]:
    target = {canonical(name): version for name, version in PY314_RPMS.items()}
    dropped = []  # type: List[str]
    moved = []  # type: List[str]
    for name, version in sorted(installed_rpms(node, "squirro-python311-").items()):
        if is_squirro_package(name) or canonical(name) in VENV_TOOLS | {"virtualenv"}:
            continue
        new = target.get(canonical(name))
        if new is None:
            dropped.append(f"{name} {version}")
        elif major(new) != major(version) and not (_dated(new) and _dated(version)):
            moved.append(f"{name} {version} -> {new}")
    findings = []  # type: List[Finding]
    if dropped:
        findings.append(
            Finding(
                "PY314-RPMS",
                INFO,
                _packages(len(dropped)),
                "The Python 3.14 release no longer ships these, so after the upgrade they're "
                "only left in virtualenv311: {}.".format(", ".join(dropped)),
                "If your own scripts use one of them, install a version that works on Python "
                "3.14 into virtualenv314, or move off it. Custom assets that import one are "
                "reported under PY314-ASSETS.",
            )
        )
    if moved:
        findings.append(
            Finding(
                "PY314-RPMS",
                INFO,
                _packages(len(moved)),
                "The Python 3.14 release ships these in a new major version: {}.".format(
                    ", ".join(moved)
                ),
                "If custom assets or your own scripts use one of them, check that they work "
                "with the new version.",
            )
        )
    return findings


# --- Hardcoded paths ---------------------------------------------------------------------

PATH_PATTERNS = ("virtualenv311", "python3.11", "squirro-python311")
PATH_ROOTS = (
    "/etc/crontab",
    "/etc/cron.d",
    "/etc/cron.hourly",
    "/etc/cron.daily",
    "/etc/cron.weekly",
    "/etc/cron.monthly",
    "/var/spool/cron",
    "/etc/systemd/system",
    "/lib/systemd/system",
    "/usr/local/lib/systemd/system",
    "/etc/nginx",
    "/etc/squirro",
    "/etc/sysconfig",
    "/usr/local/bin",
    "/opt/squirro",
    "/root/bin",
    "/home/*/bin",
)
# Under /opt/squirro: what packages install, which the upgrade replaces anyway, and
# miniforge's own Pythons.
PATH_SKIP = (
    "virtualenv*",
    "miniforge3",
    "wheels",
    "container-images",
    "elasticsearch",
    "nodejs",
    "phantomjs",
    "packaged_*",
    "esbuild",
)
MAX_TEXT_FILE = 1024 * 1024
# Copies nobody uses, and files the services' run scripts write again at every start
# from the configuration the upgrade updates.
PATH_SKIP_SUFFIXES = (
    ".rpmnew",
    ".rpmsave",
    ".rpmorig",
    ".orig",
    ".bak",
    ".old",
    ".disabled",
    "~",
)
PATH_SKIP_GENERATED = ("/etc/squirro/*.d/docker.env",)
# Where packages install their units. /lib is /usr/lib on EL 8 and 9, and rpm records
# the spelling the package was built with.
PACKAGED_UNIT_DIRS = ("/lib/systemd/system/", "/usr/lib/systemd/system/")
# Services Squirro no longer ships. Nothing reads what they leave behind, even the .ini
# files squirro-ansible keeps writing for some of them.
REMOVED_SERVICES = (
    "content",
    "fingerprint",
    "relatedstory",
    "thumbler",
    "trends",
    "webshot",
)
REMOVED_SERVICE_FILE = re.compile(
    r"^/etc/squirro/({0})\.ini$|/sq({0})d\.service(\.d/|$)".format(
        "|".join(REMOVED_SERVICES)
    )
)


# rpm's file flags: a configuration file that upgrades keep when it was changed.
CONFIG_NOREPLACE = 1 | 16
DIGESTS_BY_LENGTH = {
    32: "md5",
    40: "sha1",
    56: "sha224",
    64: "sha256",
    96: "sha384",
    128: "sha512",
}


class OwnedFile(NamedTuple):
    flags: int
    digest: str


def squirro_owned_files(node: Node) -> Dict[str, OwnedFile]:
    result = node.run(
        [
            "rpm",
            "-qa",
            "--qf",
            "[%{FILEFLAGS} %{FILEDIGESTS} %{FILENAMES}\\n]",
            "squirro-*",
        ]
    )
    if result.returncode != 0:
        raise CheckNotRun("Couldn't list the files of Squirro's packages with rpm.")
    owned = {}  # type: Dict[str, OwnedFile]
    for line in result.stdout.split("\n"):
        fields = line.split(" ", 2)
        if len(fields) == 3 and fields[0].isdigit():
            owned[fields[2]] = OwnedFile(int(fields[0]), fields[1])
    return owned


def _kept_by_upgrade(entry: OwnedFile, data: bytes) -> bool:
    """A configuration file changed since its package installed it: upgrades keep it, and
    write the package's new copy next to it as .rpmnew when that copy changed."""
    algorithm = DIGESTS_BY_LENGTH.get(len(entry.digest))
    if entry.flags & CONFIG_NOREPLACE != CONFIG_NOREPLACE or algorithm is None:
        return False
    digest = hashlib.new(algorithm, data, usedforsecurity=False).hexdigest()
    return digest != entry.digest.lower()


def _owned_entry(owned: Dict[str, OwnedFile], absolute: str) -> Optional[OwnedFile]:
    entry = owned.get(absolute)
    if entry is None and absolute.startswith(PACKAGED_UNIT_DIRS):
        other = absolute[4:] if absolute.startswith("/usr/") else "/usr" + absolute
        entry = owned.get(other)
    return entry


def _kept_unit_finding(node: Node, absolute: str, number: int, pattern: str) -> Finding:
    """A packaged unit changed by hand: rpm keeps it and writes the new one as .rpmnew,
    so the service still starts from virtualenv311, which the upgrade removes."""
    name = absolute.rsplit("/", 1)[1]
    drop_in = f"/etc/systemd/system/{name}.d/"
    if node.mode == "after":
        problem = (
            f"Refers to Python 3.11 ({pattern}). The upgrade kept this changed unit, so "
            "the service won't start."
        )
        action = (
            f"Replace it with {absolute}.rpmnew and carry your changes over as a drop-in "
            f"in {drop_in}, then run systemctl daemon-reload and restart the service."
        )
    else:
        problem = (
            f"Refers to Python 3.11 ({pattern}). A Squirro package installed this unit and "
            "it was changed since, so upgrading the package keeps it and writes the new "
            f"unit as {name}.rpmnew: the service won't start after the upgrade."
        )
        action = (
            f"Move your changes into a drop-in in {drop_in} and remove them from this "
            "file, so the upgrade replaces it. Or, right after the upgrade, replace it "
            f"with {absolute}.rpmnew and add the drop-in then."
        )
    return Finding(
        "PY314-PATHS", ACTION_NEEDED, f"{absolute}:{number}", problem, action
    )


def _skipped_under_opt(path: Path, opt: Path) -> bool:
    try:
        first = path.relative_to(opt).parts[0]
    except (ValueError, IndexError):
        return False
    return any(fnmatch.fnmatch(first, pattern) for pattern in PATH_SKIP)


def _text(path: Path) -> Optional[bytes]:
    """The file's content, or None for big or binary files. Raises OSError."""
    if path.stat().st_size > MAX_TEXT_FILE:
        return None
    data = path.read_bytes()
    return None if b"\0" in data[:8192] else data


def check_paths(node: Node) -> List[Finding]:
    findings = []  # type: List[Finding]
    rpm_action = "Check that the rpm command works on this node, then rerun the script."
    try:
        owned = squirro_owned_files(node)
        ownership_known = True
    except CheckNotRun:
        owned = {}
        ownership_known = False
        findings.append(
            Finding(
                "PY314-PATHS",
                NOT_CHECKED,
                "-",
                "Couldn't tell which files Squirro's packages own, which the upgrade replaces "
                "anyway, so the files that refer to Python 3.11 weren't checked.",
                rpm_action,
            )
        )
    myself = os.path.realpath(__file__)
    opt = node.path("/opt/squirro")
    action = (
        f"Point it at {VENV314} before removing virtualenv311."
        if node.mode == "after"
        else f"Point it at {VENV314} (python3.14) once the node is upgraded."
    )
    roots = []  # type: List[Path]
    for root in PATH_ROOTS:
        if "/*/" not in root:
            roots.append(node.path(root))
            continue
        parent, _, below = root.partition("/*/")
        try:
            entries = sorted(node.path(parent).iterdir())
        except FileNotFoundError:
            entries = []
        except PermissionError:
            entries = []
            findings.append(
                not_checked(
                    "PY314-PATHS",
                    parent,
                    "Couldn't list this folder (permission denied).",
                )
            )
        roots.extend(entry / below for entry in entries)
    for root in roots:
        unreadable = []  # type: List[str]
        try:
            kind = path_kind(root)
        except PermissionError:
            kind = None
            unreadable.append(str(root))
        if kind == "file" and not root.is_symlink():
            files = [root]
        elif kind == "dir":
            files = []
            for dirpath, dirnames, filenames in os.walk(
                str(root), onerror=lambda e: unreadable.append(e.filename)
            ):
                here = Path(dirpath)
                dirnames[:] = sorted(
                    d for d in dirnames if not _skipped_under_opt(here / d, opt)
                )
                files.extend(here / name for name in sorted(filenames))
        else:
            files = []
        for path in files:
            if path.is_symlink() or os.path.realpath(str(path)) == myself:
                continue
            absolute = "/" + str(path.relative_to(node.root))
            if REMOVED_SERVICE_FILE.search(absolute):
                continue
            entry = _owned_entry(owned, absolute)
            if (
                (entry and entry.flags & CONFIG_NOREPLACE != CONFIG_NOREPLACE)
                or absolute.endswith(PATH_SKIP_SUFFIXES)
                or any(
                    fnmatch.fnmatch(absolute, pattern)
                    for pattern in PATH_SKIP_GENERATED
                )
            ):
                continue
            try:
                data = _text(path)
            except OSError:
                unreadable.append(absolute)
                continue
            if data is None or (entry and not _kept_by_upgrade(entry, data)):
                continue
            lines = data.decode("utf-8", errors="replace").splitlines()
            for number, line in enumerate(lines, 1):
                pattern = next((p for p in PATH_PATTERNS if p in line), None)
                if not pattern:
                    continue
                if not ownership_known:
                    findings.append(
                        Finding(
                            "PY314-PATHS",
                            NOT_CHECKED,
                            f"{absolute}:{number}",
                            f"Refers to Python 3.11 ({pattern}). Without rpm's file list, it "
                            "isn't known whether a Squirro package installed this file, in "
                            "which case the upgrade replaces it.",
                            rpm_action,
                        )
                    )
                    continue
                if entry and absolute.startswith(PACKAGED_UNIT_DIRS):
                    findings.append(_kept_unit_finding(node, absolute, number, pattern))
                    continue
                problem = f"Refers to Python 3.11 ({pattern})."
                if entry and node.mode == "before":
                    findings.append(
                        Finding(
                            "PY314-PATHS",
                            INFO,
                            f"{absolute}:{number}",
                            problem + " A Squirro package installed this configuration "
                            "file and it was changed since, so upgrading the package keeps "
                            "this line as it is.",
                            f"After the upgrade, point it at {VENV314} if it still refers to "
                            "Python 3.11, then rerun this script.",
                        )
                    )
                    continue
                if entry:
                    problem += " The upgrade kept this changed configuration file."
                findings.append(
                    Finding(
                        "PY314-PATHS",
                        ACTION_NEEDED,
                        f"{absolute}:{number}",
                        problem,
                        action,
                    )
                )
        if unreadable:
            findings.append(
                not_checked(
                    "PY314-PATHS",
                    "/" + str(root.relative_to(node.root)),
                    f"Couldn't read {len(unreadable)} file(s) or folder(s) here.",
                )
            )
    return findings


# --- Database driver ---------------------------------------------------------------------

PYMYSQL_URL = "mysql+pymysql://"
MARIADB_URL = "mysql+mariadbconnector://"
# A database URL encrypted by one of Squirro's crypt keepers (CK_CMD::, CK_ENV::, ...).
ENCRYPTED_DB_URL = re.compile(r"^\s*db\s*[=:]\s*CK_[A-Z]+::", re.IGNORECASE)


def check_db(node: Node) -> List[Finding]:
    """Configuration that connects to MySQL with PyMySQL. Squirro uses the MariaDB
    connector, and the upgrade doesn't install PyMySQL into virtualenv314."""
    switch = (
        f"replace {PYMYSQL_URL} with {MARIADB_URL}, the driver Squirro has used since "
        "3.10.2, and restart the services that read the file."
    )
    if node.mode == "after":
        if node.venv314 is not None and "pymysql" in venv_distributions(node.venv314):
            problem = (
                f"Connects to MySQL with PyMySQL ({PYMYSQL_URL}). The services that read "
                "this file run only because PyMySQL is installed in virtualenv314, and "
                "Squirro doesn't support it."
            )
        else:
            problem = (
                f"Connects to MySQL with PyMySQL ({PYMYSQL_URL}), which isn't installed in "
                "virtualenv314, so the services that read this file can't start."
            )
        action = switch[0].upper() + switch[1:]
    else:
        problem = (
            f"Connects to MySQL with PyMySQL ({PYMYSQL_URL}). The upgrade doesn't install "
            "PyMySQL for Python 3.14, so the services that read this file won't start "
            "after the upgrade."
        )
        action = f"Before the upgrade, {switch}"
    findings = []  # type: List[Finding]
    for ini in sorted(node.path("/etc/squirro").glob("*.ini")):
        if ini.stem in REMOVED_SERVICES:
            continue
        absolute = "/" + str(ini.relative_to(node.root))
        try:
            lines = ini.read_text(errors="replace").splitlines()
        except FileNotFoundError:
            continue
        except OSError:
            findings.append(
                not_checked(
                    "PY314-DB",
                    absolute,
                    "Couldn't read this configuration file, so the database driver it "
                    "uses wasn't checked.",
                )
            )
            continue
        for number, line in enumerate(lines, 1):
            if line.lstrip().startswith(("#", ";")):
                continue
            location = f"{absolute}:{number}"
            if PYMYSQL_URL in line:
                findings.append(
                    Finding("PY314-DB", ACTION_NEEDED, location, problem, action)
                )
            elif ENCRYPTED_DB_URL.match(line):
                findings.append(
                    not_checked(
                        "PY314-DB",
                        location,
                        "This database URL is encrypted, so the driver it uses couldn't "
                        "be told.",
                        f"Check that it starts with {MARIADB_URL}, not {PYMYSQL_URL}.",
                    )
                )
    return findings


# --- Trained models ----------------------------------------------------------------------

ML_CONFIG = "/etc/squirro/machinelearning.ini"
# Steps whose scikit-learn models load on 3.14 with a version warning.
SKLEARN_STEPS = frozenset(
    [("classifier", "sklearn"), ("projector", "sklearn"), ("embedder", "sklearn_tfidf")]
)  # type: FrozenSet[Tuple[str, str]]


class Workflow(NamedTuple):
    id: str
    project_id: str
    name: str
    config: Dict[str, Any]


# Runs in a child process with the services' environment (/etc/sysconfig/squirro puts
# Squirro's own MariaDB client library on LD_LIBRARY_PATH, which only counts when a
# process starts). It prints one JSON object and never the error's message, which may
# carry the database URL.
WORKFLOW_READER = """
import json, sys
try:
    from squirro.common.config import get_config
    from squirro.common.db import create_engine
    engine = create_engine(get_config("squirro.service.machinelearning"), "machinelearning")
    try:
        with engine.connect() as connection:
            rows = connection.exec_driver_sql(
                "SELECT id, project_id, name, config FROM machinelearning_workflows"
            ).fetchall()
    finally:
        engine.dispose()
    result = {"workflows": [
        [str(r[0]), str(r[1]), str(r[2]), r[3].decode() if isinstance(r[3], bytes) else r[3]]
        for r in rows
    ]}
except Exception as exc:
    result = {"error": type(exc).__name__}
sys.stdout.write("\\n" + json.dumps(result) + "\\n")
"""
SERVICE_ENVIRONMENT = (
    "set -a; for f in /etc/sysconfig/squirro /etc/sysconfig/squirro_venv_default; do "
    '[ -r "$f" ] && . "$f"; done; set +a; exec "$0" -B -W ignore -c "$1"'
)


def load_workflows(node: Node) -> Optional[List[Workflow]]:
    """The ML workflows, or None when the machinelearning service isn't on this node.
    Read through the Squirro libraries of the virtualenv the script runs in, so the
    database settings are read (and decrypted) the way the service reads them."""
    if not node.path(ML_CONFIG).exists():
        return None
    result = node.run(
        ["bash", "-c", SERVICE_ENVIRONMENT, sys.executable, WORKFLOW_READER]
    )
    lines = result.stdout.strip().splitlines()
    try:
        answer = json.loads(lines[-1]) if result.returncode == 0 and lines else None
    except ValueError:
        answer = None
    if not isinstance(answer, dict):
        raise CheckNotRun(
            "Couldn't read the ML workflows: the reader stopped unexpectedly.",
            "Check that this node reaches the machinelearning database, then rerun the script as root.",
        )
    if answer.get("error") in ("ImportError", "ModuleNotFoundError"):
        raise CheckNotRun(
            "The Squirro libraries couldn't be loaded, so the ML workflows couldn't be read.",
            f"Run the script with {VENV311}/bin/python.",
        )
    if "error" in answer:
        raise CheckNotRun(
            "Couldn't read the ML workflows ({}).".format(answer["error"]),
            "Check that this node reaches the machinelearning database, then rerun the script as root.",
        )
    workflows = []  # type: List[Workflow]
    for workflow_id, project_id, name, config in answer.get("workflows", []):
        if isinstance(config, str):
            try:
                config = json.loads(config)
            except ValueError:
                continue
        if isinstance(config, dict):
            workflows.append(Workflow(workflow_id, project_id, name, config))
    return workflows


def model_steps(config: Dict[str, Any]) -> List[Tuple[str, str]]:
    """Every (step, type) in a workflow's pipeline, nested ones (a kfold step's
    classifier_params) included."""
    steps = []  # type: List[Tuple[str, str]]

    def walk(value: Any) -> None:
        if isinstance(value, dict):
            if isinstance(value.get("step"), str) and isinstance(
                value.get("type"), str
            ):
                steps.append((value["step"], value["type"]))
            for child in value.values():
                walk(child)
        elif isinstance(value, list):
            for child in value:
                walk(child)

    walk(config.get("pipeline", []))
    return steps


def uses_tensorflow_transformer(config: Dict[str, Any]) -> bool:
    """Whether a step of the workflow's pipeline, nested ones included, embeds with the
    "tensorflow" transformer (Universal Sentence Encoder), which libNLP no longer has."""

    def walk(value: Any) -> bool:
        if isinstance(value, dict):
            if value.get("transformer") == "tensorflow":
                return True
            return any(walk(child) for child in value.values())
        if isinstance(value, list):
            return any(walk(child) for child in value)
        return False

    return walk(config.get("pipeline", []))


def check_models(
    node: Node, load: Callable[[Node], Optional[List[Workflow]]] = load_workflows
) -> List[Finding]:
    workflows = load(node)
    if workflows is None:
        return [
            Finding(
                "PY314-MODELS",
                NOT_APPLICABLE,
                "-",
                "The machinelearning service isn't configured on this node.",
                "Run the script on the node that runs it.",
            )
        ]
    findings = []  # type: List[Finding]
    for workflow in workflows:
        steps = model_steps(workflow.config)
        location = (
            f'project {workflow.project_id}, workflow "{workflow.name}" ({workflow.id})'
        )
        if any(kind == "automl" for _, kind in steps):
            findings.append(
                Finding(
                    "PY314-MODELS",
                    ACTION_NEEDED,
                    location,
                    "Its AutoML model, trained on Python 3.11, doesn't load on Python 3.14.",
                    "Retrain the workflow's model after the upgrade.",
                )
            )
        if uses_tensorflow_transformer(workflow.config):
            findings.append(
                Finding(
                    "PY314-MODELS",
                    ACTION_NEEDED,
                    location,
                    "It embeds with the tensorflow transformer (Universal Sentence Encoder), which "
                    "the Python 3.14 release no longer has, so the workflow fails.",
                    "Switch its embedder to the sentence_transformer transformer and retrain it; "
                    "for an AI Studio model, edit and save the model to rebuild its workflow.",
                )
            )
        if any(step in SKLEARN_STEPS for step in steps):
            findings.append(
                Finding(
                    "PY314-MODELS",
                    INFO,
                    location,
                    "Its scikit-learn models load and predict as before on Python 3.14, with a "
                    "warning that they were saved by another scikit-learn version.",
                    "Retraining after the upgrade is recommended.",
                )
            )
    return findings


# --- Operating system --------------------------------------------------------------------

EL_IDS = frozenset(["rocky", "rhel", "almalinux", "centos", "ol"])  # type: FrozenSet[str]
SQUIRRO_MIRROR = "mirror.squirro.net"


def _el_version(node: Node) -> Optional[Tuple[int, Optional[int]]]:
    release = node.os_release
    if release.get("ID") not in EL_IDS:
        return None
    match = re.match(r"(\d+)(?:\.(\d+))?", release.get("VERSION_ID", ""))
    if not match:
        return None
    minor = match.group(2)
    return int(match.group(1)), int(minor) if minor else None


def _squirro_repo_hosts(node: Node, unreadable: List[Path]) -> List[str]:
    """The hosts of the Squirro repositories' baseurls ("" for file://), from every
    section whose name starts with "squirro" ([squirro], [squirro-stable], ...)."""
    hosts = []  # type: List[str]
    for path in sorted(node.path("/etc/yum.repos.d").glob("*.repo")):
        parser = configparser.ConfigParser(interpolation=None, strict=False)
        try:
            parser.read_string(path.read_text(errors="replace"))
        except OSError:
            unreadable.append(path)
            continue
        except configparser.Error:
            continue
        for section in parser.sections():
            if section.lower().startswith("squirro"):
                for url in parser.get(section, "baseurl", fallback="").split():
                    parsed = urllib.parse.urlparse(url)
                    hosts.append(
                        "" if parsed.scheme == "file" else (parsed.hostname or "")
                    )
    return hosts


def check_os(node: Node) -> List[Finding]:
    version = _el_version(node)
    if version is None:
        return [
            Finding(
                "PY314-OS",
                NOT_CHECKED,
                "/etc/os-release",
                "Couldn't tell which Enterprise Linux release this node runs.",
                "Squirro's Python 3.14 packages exist for EL8 and EL9; check the OS by hand.",
            )
        ]
    major_version, minor = version
    if major_version == 9 and minor is None:
        return [
            Finding(
                "PY314-OS",
                NOT_CHECKED,
                "/etc/os-release",
                "Its VERSION_ID has no minor release, so whether the OS has Python 3.14 (EL 9.8 "
                "on) couldn't be told.",
                "Check that dnf finds python3.14 (dnf info python3.14) before upgrading Squirro.",
            )
        ]
    if major_version == 9 and minor < 8:
        return [
            Finding(
                "PY314-OS",
                ACTION_NEEDED,
                f"EL {major_version}.{minor}",
                "Python 3.14 comes from the OS's AppStream repository, which has it from EL 9.8 on.",
                "Update the OS to 9.8 or later before upgrading Squirro.",
            )
        ]
    if major_version == 8:
        unreadable = []  # type: List[Path]
        hosts = _squirro_repo_hosts(node, unreadable)
        if unreadable:
            return [
                not_checked(
                    "PY314-OS",
                    "/" + str(path.relative_to(node.root)),
                    "Couldn't read this repository file, so where Python 3.14 comes from couldn't be told.",
                )
                for path in unreadable
            ]
        if hosts and any(host != SQUIRRO_MIRROR for host in hosts):
            return [
                Finding(
                    "PY314-OS",
                    INFO,
                    "the [squirro] repository in /etc/yum.repos.d",
                    "On EL8, Python 3.14 comes from Squirro's repository of the target release, and "
                    "this node's Squirro repository isn't Squirro's mirror.",
                    "Make sure your mirror carries python3.14, python3.14-libs and "
                    "python3.14-pip-wheel for EL8.",
                )
            ]
    return []


# --- Trusted CA certificates -------------------------------------------------------------

CA_ANCHORS = (
    "/etc/pki/ca-trust/source/anchors",
    "/usr/share/pki/ca-trust-source/anchors",
)
# The distribution's bundles of public roots, which aren't what breaks.
DISTRIBUTION_BUNDLES = frozenset(
    [
        "/etc/pki/tls/certs/ca-bundle.crt",
        "/etc/pki/tls/certs/ca-bundle.trust.crt",
        "/etc/ssl/certs/ca-bundle.crt",
        "/etc/ssl/certs/ca-bundle.trust.crt",
        "/etc/pki/tls/cert.pem",
    ]
)  # type: FrozenSet[str]
CA_OPTION_SUFFIXES = ("ca_certs", "ca_file", "cafile", "pem_path", "ssl_ca")
# The CA Elasticsearch's security auto-configuration creates; the storage node's own
# scripts verify against this file directly.
ES_HTTP_CA = "/etc/elasticsearch/certs/http_ca.crt"
ES_HTTP_CA_ACTION = (
    "This is Elasticsearch's HTTP CA. Reissue it before the upgrade with the same key "
    "(Elasticsearch keeps it in /etc/elasticsearch/certs/http.p12, alias http_ca) and "
    "subject, with critical Basic Constraints, a Key Usage extension (keyCertSign, cRLSign) "
    "and a Subject Key Identifier. Replace this file and its copies among the system's "
    "trust anchors with it, then run update-ca-trust. The certificates it issued still "
    "chain to it, so Elasticsearch needs no restart."
)
# update-ca-trust also takes p11-kit's TRUSTED CERTIFICATE blocks, and DER files.
PEM_CERTIFICATE = re.compile(
    r"-----BEGIN (?:TRUSTED )?CERTIFICATE-----.+?-----END (?:TRUSTED )?CERTIFICATE-----",
    re.DOTALL,
)


def _env_values(path: Path, key: str, unreadable: List[Path]) -> List[str]:
    values = []  # type: List[str]
    try:
        for line in path.read_text(errors="replace").splitlines():
            name, sep, value = line.strip().partition("=")
            if sep and name.strip() == key:
                values.append(value.strip().strip("\"'"))
    except FileNotFoundError:
        pass
    except OSError:
        unreadable.append(path)
    return values


def ca_files(node: Node, unreadable: Optional[List[Path]] = None) -> List[str]:
    """The CA files the installation adds to the trust, as configured (absolute paths).
    Configuration files that can't be read are added to `unreadable`."""
    unread = [] if unreadable is None else unreadable  # type: List[Path]
    found = set()  # type: Set[str]
    for directory in CA_ANCHORS:
        for path in node.path(directory).glob("*"):
            try:
                if path_kind(path) != "file":
                    continue
            except PermissionError:
                pass  # check_tls reports it as unreadable
            found.add(f"{directory}/{path.name}")
    try:
        if path_kind(node.path(ES_HTTP_CA)) == "file":
            found.add(ES_HTTP_CA)
    except PermissionError:
        found.add(ES_HTTP_CA)  # check_tls reports it as unreadable
    for ini in sorted(node.path("/etc/squirro").glob("*.ini")):
        if ini.stem in REMOVED_SERVICES:
            continue
        parser = configparser.ConfigParser(interpolation=None, strict=False)
        try:
            parser.read_string(ini.read_text(errors="replace"))
        except OSError:
            unread.append(ini)
            continue
        except configparser.Error:
            continue
        for section in parser.sections():
            for option, value in parser.items(section):
                if option.endswith(CA_OPTION_SUFFIXES) and value.startswith("/"):
                    found.add(value.strip())
    env_files = [node.path("/etc/sysconfig/squirro")] + sorted(
        node.path("/etc/squirro/genai.d").glob("*.env")
    )
    for env_file in env_files:
        found.update(
            v for v in _env_values(env_file, "SQ_CA_FILE", unread) if v.startswith("/")
        )
    # Bundles shipped inside a virtualenv (certifi's) are public roots too.
    return sorted(
        path for path in found - DISTRIBUTION_BUNDLES if "/site-packages/" not in path
    )


def _certificate_problems(text: str) -> List[str]:
    """What OpenSSL 3's strict verification, the default from Python 3.13 on, refuses
    about this certificate (checked against real handshakes in the tests)."""
    problems = []  # type: List[str]
    if re.search(r"X509v3 Basic Constraints:.*\n\s*CA:TRUE", text):
        if not re.search(r"X509v3 Basic Constraints: critical", text):
            problems.append("its Basic Constraints aren't marked critical")
        if "X509v3 Key Usage" not in text:
            problems.append("it has no Key Usage extension")
        if "X509v3 Subject Key Identifier" not in text:
            problems.append(
                "it has no Subject Key Identifier, so what it issues can't carry the Authority Key "
                "Identifier that's required"
            )
    issuer = re.search(r"Issuer: (.*)", text)
    subject = re.search(r"Subject: (.*)", text)
    self_signed = bool(
        issuer and subject and issuer.group(1).strip() == subject.group(1).strip()
    )
    if not self_signed:
        key_id = re.search(
            r"X509v3 Authority Key Identifier:\s*\n\s*(?:keyid:)?(?:[0-9A-Fa-f]{2}:){4,}",
            text,
        )
        if not key_id:
            problems.append("it has no Authority Key Identifier with a key ID")
    return problems


PYTHONS_314 = (f"{VENV314}/bin/python", "/usr/bin/python3.14")


def _openssl_major(node: Node) -> int:
    """The major version of the OpenSSL Python 3.14 uses: python3.14's own once it's
    installed (a build may bring its own), else the system's."""
    result = node.run(["openssl", "version"])
    if result.returncode == 127:
        raise CheckNotRun(
            "The openssl command isn't available, so the CA certificates couldn't be checked.",
            "Check the certificates in the files listed by hand, or rerun where openssl is installed.",
        )
    for python in PYTHONS_314:
        if node.path(python).exists():
            linked = node.run(
                [python, "-I", "-c", "import ssl; print(ssl.OPENSSL_VERSION_INFO[0])"]
            )
            if linked.returncode == 0 and linked.stdout.strip().isdigit():
                return int(linked.stdout.strip())
    match = re.search(r"OpenSSL (\d+)\.", result.stdout)
    return int(match.group(1)) if match else 3


def changed_certifi_bundle(node: Node) -> Optional[Finding]:
    """certifi's CA bundle in virtualenv311, when it differs from what its RECORD says
    was installed: virtualenv314 gets a fresh copy."""
    if node.venv311 is None:
        return None
    for info in sorted(
        node.venv311.glob("lib*/python3.*/site-packages/certifi-*.dist-info")
    ):
        bundle = info.parent / "certifi" / "cacert.pem"
        location = "/" + str(bundle.relative_to(node.root))
        try:
            record = (info / "RECORD").read_text(errors="replace")
            data = bundle.read_bytes()
        except FileNotFoundError:
            continue
        except OSError:
            return not_checked(
                "PY314-TLS",
                location,
                "Couldn't read certifi's CA bundle or its RECORD, so changes to it weren't "
                "checked.",
            )
        for line in record.splitlines():
            name, _, rest = line.partition(",")
            if name != "certifi/cacert.pem" or not rest.startswith("sha256="):
                continue
            expected = rest[len("sha256=") :].split(",")[0]
            actual = base64.urlsafe_b64encode(hashlib.sha256(data).digest())
            if actual.rstrip(b"=").decode() == expected:
                return None
            return Finding(
                "PY314-TLS",
                ACTION_NEEDED,
                location,
                "Changed since certifi installed it, usually by adding CA certificates by hand. "
                "The upgrade installs a fresh copy into virtualenv314 without them, and that's "
                "the copy the services' ssl_ca_certs setting and Python's HTTP clients use.",
                f"Keep the added certificates, and add them to the same file in {VENV314} "
                "right after the upgrade.",
            )
    return None


def check_tls(node: Node) -> List[Finding]:
    certifi = changed_certifi_bundle(node)
    unreadable = []  # type: List[Path]
    files = ca_files(node, unreadable)
    found = [certifi] if certifi else []
    if not files and not unreadable:
        return found
    try:
        openssl_major = _openssl_major(node)
    except CheckNotRun as exc:
        return found + [Finding("PY314-TLS", NOT_CHECKED, "-", exc.problem, exc.action)]
    if openssl_major < 3:
        return found + [
            Finding(
                "PY314-TLS",
                NOT_APPLICABLE,
                "-",
                "The OpenSSL Python 3.14 uses on this node is older than 3, and its strict "
                "verification accepts the certificates Python 3.14 refuses with OpenSSL 3.",
                "No certificate needs reissuing on this node.",
            )
        ]
    findings = found + [
        not_checked(
            "PY314-TLS",
            "/" + str(path.relative_to(node.root)),
            "Couldn't read this configuration file, so the CA files it names weren't checked.",
        )
        for path in unreadable
    ]
    # A certificate in several files (a CA and its copies among the anchors) is reported
    # once, at its first file.
    first = {}  # type: Dict[str, Optional[int]]
    copies = {}  # type: Dict[int, List[str]]
    for configured in files:
        try:
            content = node.path(configured).read_text(errors="replace")
        except FileNotFoundError:
            continue
        except OSError:
            findings.append(
                not_checked("PY314-TLS", configured, "Couldn't read this CA file.")
            )
            continue
        pems = PEM_CERTIFICATE.findall(content)
        if not pems and content.strip():
            der = node.run(
                ["openssl", "x509", "-inform", "DER", "-in", str(node.path(configured))]
            )
            pems = PEM_CERTIFICATE.findall(der.stdout) if der.returncode == 0 else []
            if not pems:
                findings.append(
                    not_checked(
                        "PY314-TLS",
                        configured,
                        "openssl found no certificate in this file, in PEM or DER.",
                        "Check it by hand.",
                    )
                )
                continue
        for number, pem in enumerate(pems, 1):
            key = "".join(pem.split())
            if key in first:
                index = first[key]
                if index is not None:
                    copies.setdefault(index, []).append(configured)
                continue
            first[key] = None
            result = node.run(["openssl", "x509", "-noout", "-text"], pem + "\n")
            if result.returncode != 0:
                findings.append(
                    not_checked(
                        "PY314-TLS",
                        f"{configured}, certificate {number}",
                        "openssl couldn't read this certificate.",
                        "Check it by hand.",
                    )
                )
                continue
            problems = _certificate_problems(result.stdout)
            if problems:
                first[key] = len(findings)
                subject = re.search(r"Subject: (.*)", result.stdout)
                findings.append(
                    Finding(
                        "PY314-TLS",
                        ACTION_NEEDED,
                        "{}, certificate {} ({})".format(
                            configured,
                            number,
                            # OpenSSL versions differ in spacing: "CN = x" or "CN=x"
                            re.sub(r"\s*=\s*", "=", subject.group(1).strip())
                            if subject
                            else "unknown subject",
                        ),
                        "Python 3.14 refuses this certificate and everything it issued: {}.".format(
                            "; ".join(problems)
                        ),
                        ES_HTTP_CA_ACTION
                        if configured == ES_HTTP_CA
                        else "Reissue it with critical Basic Constraints, a Key Usage extension "
                        "and a Subject Key Identifier (and an Authority Key Identifier when "
                        "another CA issued it) before the upgrade.",
                    )
                )
    for index, others in copies.items():
        finding = findings[index]
        others = sorted(set(others))
        findings[index] = finding._replace(
            problem="{} The same certificate is also in {}.".format(
                finding.problem,
                others[0]
                if len(others) == 1
                else ", ".join(others[:-1]) + " and " + others[-1],
            ),
            action=ES_HTTP_CA_ACTION if ES_HTTP_CA in others else finding.action,
        )
    return findings


# --- Python 3.11 leftovers ---------------------------------------------------------------

LEFTOVER_BLOCKERS = ("PY314-PATHS", "PY314-PIP", "PY314-ASSETS")
REMOVE_COMMAND = (
    "sudo dnf remove 'squirro-python311-*' python3.11 python3.11-libs && sudo rm -rf "
    + VENV311
)


def services_left_on_311(node: Node) -> List[str]:
    """Packaged services that still start from virtualenv311: their packages have no
    Python 3.14 version, so removing Python 3.11 removes them."""
    names = []  # type: List[str]
    for unit in sorted(node.path("/usr/lib/systemd/system").glob("*.service")):
        try:
            if VENV311 in unit.read_text(errors="replace"):
                names.append(unit.stem)
        except OSError:
            continue
    return names


def check_leftovers(node: Node, earlier: Sequence[Finding] = ()) -> List[Finding]:
    packages = installed_rpms(node, "squirro-python311-")
    parts = []  # type: List[str]
    if packages:
        parts.append(f"{len(packages)} squirro-python311-* package(s)")
    if "" in installed_rpms(node, "python3.11"):
        parts.append("python3.11")
    if node.venv311 is not None:
        parts.append(VENV311)
    if not parts:
        return []
    blocking = sorted(
        {
            f.check
            for f in earlier
            if f.severity == ACTION_NEEDED and f.check in LEFTOVER_BLOCKERS
        }
    )
    unread = sorted(
        {
            f.check
            for f in earlier
            if f.severity == NOT_CHECKED and f.check in LEFTOVER_BLOCKERS
        }
    )
    if blocking or unread:
        steps = []  # type: List[str]
        if blocking:
            steps.append(
                "resolve the action-needed findings of {}".format(", ".join(blocking))
            )
        if unread:
            steps.append(
                "rerun the script with sudo, so {} can read everything".format(
                    ", ".join(unread)
                )
            )
        action = "Not yet: first {}; then remove them with: {}".format(
            " and ".join(steps), REMOVE_COMMAND
        )
    else:
        action = f"Remove them with: {REMOVE_COMMAND}"
    # Units PY314-PATHS reports were changed by hand; their packages do have a 3.14 version.
    kept = {
        f.location.rsplit(":", 1)[0].rsplit("/", 1)[-1]
        for f in earlier
        if f.check == "PY314-PATHS"
        and f.severity != NOT_CHECKED
        and f.location.startswith(PACKAGED_UNIT_DIRS)
    }
    services = [s for s in services_left_on_311(node) if f"{s}.service" not in kept]
    problem = "What's left of Python 3.11."
    if services:
        problem += (
            " These services still start from it, and removing it removes them too, "
            "since the Python 3.14 release has no package for them: {}.".format(
                ", ".join(services)
            )
        )
    return [Finding("PY314-LEFTOVERS", INFO, ", ".join(parts), problem, action)]


# (check ID, modes it runs in, function), in report order.
CHECKS = [
    ("PY314-ASSETS", ("before", "after"), check_assets),
    ("PY314-DEPS", ("before", "after"), check_deps),
    ("PY314-MODELS", ("before",), check_models),
    ("PY314-PATHS", ("before", "after"), check_paths),
    ("PY314-DB", ("before", "after"), check_db),
    ("PY314-PIP", ("before", "after"), check_pip),
    ("PY314-RPMS", ("before",), check_rpms),
    ("PY314-OS", ("before",), check_os),
    ("PY314-TLS", ("before",), check_tls),
    ("PY314-LEFTOVERS", ("after",), check_leftovers),
]  # type: List[Tuple[str, Tuple[str, ...], Callable[[Node], List[Finding]]]]


def node_facts(node: Node) -> Dict[str, Any]:
    os_release = node.os_release
    return {
        "os": os_release.get("ID"),
        "os_version": os_release.get("VERSION_ID"),
        "squirro_version": node.squirro_version,
        "roles": node.roles,
        "virtualenvs": [
            name
            for name, path in (
                ("virtualenv311", node.venv311),
                ("virtualenv314", node.venv314),
            )
            if path is not None
        ],
        "running_as_root": node.is_root,
    }


def terminal_progress(stream: Any) -> Callable[[str], None]:
    """Shows `text` on one line of `stream` when it's a terminal, replacing what was there;
    an empty text clears the line. Writes nothing otherwise, as when an agent runs this."""
    try:
        live = stream.isatty()
    except (AttributeError, ValueError):
        live = False

    def show(text: str) -> None:
        if live:
            stream.write("\r\033[K" + text)
            stream.flush()

    return show


def run_checks(
    node: Node, progress: Callable[[str], None] = lambda text: None
) -> Report:
    mode = node.mode
    findings = []  # type: List[Finding]
    if mode is not None:
        to_run = [entry for entry in CHECKS if mode in entry[1]]
        for number, (check_id, _, check) in enumerate(to_run, 1):
            # Short enough not to wrap on an 80-column terminal, which \r can't clear.
            progress(f"{TOOL}: checking {check_id} ({number}/{len(to_run)})...")
            try:
                if check_id == "PY314-LEFTOVERS":
                    findings.extend(check_leftovers(node, earlier=findings))
                else:
                    findings.extend(check(node))
            except CheckNotRun as exc:
                findings.append(
                    Finding(check_id, NOT_CHECKED, "-", exc.problem, exc.action)
                )
            except PermissionError:
                findings.append(
                    Finding(
                        check_id,
                        NOT_CHECKED,
                        "-",
                        "Couldn't read everything it needs (permission denied).",
                        SUDO_HINT,
                    )
                )
            except Exception as exc:  # noqa: BLE001 - one broken check must not stop the others
                findings.append(
                    Finding(
                        check_id,
                        NOT_CHECKED,
                        "-",
                        f"The check stopped with an error ({type(exc).__name__}).",
                        "Rerun the script; if it keeps failing, report it to Squirro support with the script's version.",
                    )
                )
    return Report(mode, node_facts(node), findings)


def summary(report: Report) -> Dict[str, int]:
    return {
        severity: sum(1 for finding in report.findings if finding.severity == severity)
        for severity in (ACTION_NEEDED, INFO, NOT_CHECKED)
    }


def exit_code(report: Report) -> int:
    counts = summary(report)
    if counts[ACTION_NEEDED]:
        return 1
    return 3 if counts[NOT_CHECKED] else 0


def render_json(report: Report) -> str:
    document = {
        "tool": TOOL,
        "version": VERSION,
        "target_release": TARGET_RELEASE,
        "mode": report.mode,
        "node": report.node,
        "summary": summary(report),
        "findings": [finding._asdict() for finding in report.findings],
    }
    return json.dumps(document, indent=2)


MODE_DESCRIPTIONS = {
    "before": "before the upgrade: what changes on Python 3.14",
    "after": "after the upgrade: what still relies on Python 3.11",
}


LINE_LOCATION = re.compile(r"^(.+):(\d+)$")


def _grouped(findings: Sequence[Finding]) -> List[Tuple[List[str], str, str]]:
    """(locations, problem, action): the lines of one file that share a problem and an
    action are listed together, and so are the files that share them."""
    numbers_of = {}  # type: Dict[Tuple[str, str, str], List[str]]
    for finding in findings:
        match = LINE_LOCATION.match(finding.location)
        where = match.group(1) if match else finding.location
        numbers = numbers_of.setdefault((where, finding.problem, finding.action), [])
        if match:
            numbers.append(match.group(2))
    locations_of = {}  # type: Dict[Tuple[str, str], List[str]]
    for (where, problem, action), numbers in numbers_of.items():
        locations_of.setdefault((problem, action), []).append(
            f"{where}:{', '.join(numbers)}" if numbers else where
        )
    return [
        (locations, problem, action)
        for (problem, action), locations in locations_of.items()
    ]


# Spaces not to break at: before a number ("numpy 2.3.2", "Python 3.14") and around "->".
NO_BREAK = re.compile(r"(?<=[A-Za-z0-9]) (?=\d)| (?=-> )|(?<= ->) ")


def _wrapped(text: str, width: int) -> List[str]:
    lines = textwrap.wrap(
        NO_BREAK.sub("\xa0", text),  # textwrap only breaks at ASCII whitespace
        width=width,
        initial_indent="      ",
        subsequent_indent="      ",
        break_long_words=False,
        break_on_hyphens=False,
    )
    return [line.replace("\xa0", " ") for line in lines]


def _section(
    lines: List[str],
    title: str,
    findings: Sequence[Finding],
    check_ids: List[str],
    width: int,
) -> None:
    if not findings:
        return
    lines.extend(["", f"{title} ({len(findings)})"])
    for check_id in check_ids:
        of_check = [f for f in findings if f.check == check_id]
        if not of_check:
            continue
        lines.append(f"  {check_id}")
        for locations, problem, action in _grouped(of_check):
            lines.extend(f"    {where}" for where in locations if where != "-")
            lines.extend(_wrapped(problem, width))
            lines.extend(_wrapped(f"What to do: {action}", width))


def render_text(report: Report) -> str:
    lines = [
        "{} {}: checks for the move to Python 3.14{}".format(
            TOOL, VERSION, f" (Squirro {TARGET_RELEASE})" if TARGET_RELEASE else ""
        )
    ]
    facts = report.node
    if report.mode is None:
        lines.append(
            "No Squirro virtualenv on this node (a storage-only node has nothing to check)."
        )
        return "\n".join(lines) + "\n"
    roles = facts.get("roles") or []
    lines.append(
        "Node: {} {}, Squirro {}, {}{}".format(
            facts.get("os") or "unknown OS",
            facts.get("os_version") or "",
            facts.get("squirro_version") or "unknown",
            " and ".join(roles) + " node, " if roles else "",
            ", ".join(facts.get("virtualenvs") or []),
        )
    )
    lines.append(f"Mode: {MODE_DESCRIPTIONS.get(report.mode, report.mode)}")
    counts = summary(report)
    rest = f"{counts[INFO]} for your information, {counts[NOT_CHECKED]} not checked."
    lines.append(
        "Summary: {} need action{}, {}".format(
            counts[ACTION_NEEDED],
            " (listed last)" if counts[ACTION_NEEDED] else "",
            rest,
        )
    )
    check_ids = [check_id for check_id, modes, _ in CHECKS if report.mode in modes]
    for finding in report.findings:
        if finding.check not in check_ids:
            check_ids.append(finding.check)

    def of_severity(severity: str) -> List[Finding]:
        return [f for f in report.findings if f.severity == severity]

    width = min(100, shutil.get_terminal_size((100, 24)).columns)

    # What needs action comes last: in a terminal, that's what's on screen at the end.
    _section(lines, "For your information", of_severity(INFO), check_ids, width)
    _section(lines, "Not applicable", of_severity(NOT_APPLICABLE), check_ids, width)
    found = {finding.check for finding in report.findings}
    nothing = [check_id for check_id in check_ids if check_id not in found]
    if nothing:
        lines.extend(["", "Nothing found: {}.".format(", ".join(nothing))])
    _section(lines, "Not checked", of_severity(NOT_CHECKED), check_ids, width)
    _section(lines, "Action needed", of_severity(ACTION_NEEDED), check_ids, width)
    lines.append("")
    lines.append(f"Summary: {counts[ACTION_NEEDED]} need action, {rest}")
    if counts[NOT_CHECKED] and not facts.get("running_as_root"):
        lines.append("Some checks couldn't read everything: rerun with sudo.")
    if not counts[ACTION_NEEDED] and not counts[INFO]:
        lines.append(
            "Nothing found in what could be checked, but some things weren't checked: see above."
            if counts[NOT_CHECKED]
            else "Nothing to do on this node."
        )
    return "\n".join(lines) + "\n"


def interpreter_problem() -> Optional[str]:
    current = tuple(sys.version_info[:2])
    if current in ((3, 11), (3, 14)):
        return None
    return (
        f"{TOOL} runs with Squirro's own Python, not Python {current[0]}.{current[1]}: use {VENV311}/bin/python before "
        f"the upgrade, or {VENV314}/bin/python after it."
    )


def main(argv: Optional[Sequence[str]] = None) -> int:
    sys.dont_write_bytecode = True  # read-only: no __pycache__ anywhere
    problem = interpreter_problem()
    if problem:
        sys.stderr.write(problem + "\n")
        return 2
    parser = argparse.ArgumentParser(prog=TOOL, description=__doc__.splitlines()[0])
    parser.add_argument(
        "--json", action="store_true", help="print the report as one JSON document"
    )
    parser.add_argument("--version", action="version", version=f"{TOOL} {VERSION}")
    parser.add_argument("--root", default="/", help=argparse.SUPPRESS)
    args = parser.parse_args(argv)
    progress = terminal_progress(sys.stderr)
    progress(f"{TOOL} {VERSION}: checking this node (read-only)...")
    try:
        try:
            report = run_checks(Node(Path(args.root)), progress)
        finally:
            progress("")
        output = render_json(report) + "\n" if args.json else render_text(report)
        if hasattr(sys.stdout, "reconfigure"):
            # File names that aren't valid UTF-8 come back as surrogates.
            sys.stdout.reconfigure(errors="backslashreplace")
        sys.stdout.write(output)
        sys.stdout.flush()
    except Exception as exc:  # noqa: BLE001 - say so instead of a traceback
        sys.stderr.write(f"{TOOL} failed ({type(exc).__name__}).\n")
        return 2
    return exit_code(report)


if __name__ == "__main__":
    sys.exit(main())
