"""Do the page's files run with no internet, once the two models are downloaded?

    python offline.py

It sets HF_HUB_OFFLINE=1, which tells the Hugging Face libraries to read only
the cache folder on this computer. To be sure, it also makes every attempt to
open a connection to another computer fail, and counts the attempts. Then it
runs the page's own ask.py. If ask.py still answers, nothing left the computer.
"""
import os
import socket
import sys
from pathlib import Path

os.environ["HF_HUB_OFFLINE"] = "1"      # must be set before the libraries are loaded

PAGE_FILES = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(PAGE_FILES))
QUESTION = "What is the password for the internet?"
ATTEMPTS = []
REAL_CONNECT = socket.socket.connect


def refuse(self, address, *rest):
    """Stands in for socket.connect: this computer itself is allowed, nothing else."""
    host = address[0] if isinstance(address, tuple) else str(address)
    if host in ("127.0.0.1", "::1", "localhost"):
        return REAL_CONNECT(self, address, *rest)
    ATTEMPTS.append(host)
    raise OSError(f"offline.py allows no connection to {host}")


def main():
    socket.socket.connect = refuse
    import ask                          # the page's own file, loaded with the net shut
    os.chdir(PAGE_FILES)                # ask.py reads the handbook from where it runs
    sys.argv = ["ask.py", QUESTION]
    ask.main()
    print()
    print(f"HF_HUB_OFFLINE={os.environ['HF_HUB_OFFLINE']}."
          f" Connections to other computers attempted: {len(ATTEMPTS)}.")
    print("ask.py answered from the handbook and the two models on this computer.")


if __name__ == "__main__":
    main()
