"""Find an already installed TOML-capable Python when stock macOS Python is older."""

import os
from pathlib import Path
import shutil
import subprocess
import sys


def require_python311(script):
    if sys.version_info >= (3, 11):
        return
    names = ["python3.14", "python3.13", "python3.12", "python3.11"]
    candidates = [shutil.which(name) for name in names]
    candidates.extend(str(Path(prefix) / name)
                      for prefix in ("/opt/homebrew/bin", "/usr/local/bin") for name in names)
    for candidate in dict.fromkeys(candidates):
        if not candidate or not os.access(candidate, os.X_OK):
            continue
        try:
            probe = subprocess.run([candidate, "-c", "import sys;sys.exit(sys.version_info < (3,11))"],
                                   capture_output=True, check=False, timeout=3)
            if probe.returncode == 0:
                os.execv(candidate, [candidate, str(script), *sys.argv[1:]])
        except (OSError, subprocess.TimeoutExpired):
            continue
    raise SystemExit("Codex settings configuration requires an installed Python 3.11 or newer")
