"""what_it_gets.py - what does Paperclip hand to a program it starts?

    python what_it_gets.py

Hires an agent whose program prints the names of its PAPERCLIP_ environment
variables, wakes it by hand, and prints what came back. It also prints the
versions this page was run with.
"""
import platform
import subprocess
import sys
import time

import requests

import scratch

PROGRAM = ("import os; print(' '.join(sorted(name for name in os.environ "
           "if name.startswith('PAPERCLIP_'))))")
USED = ["PAPERCLIP_API_URL", "PAPERCLIP_API_KEY", "PAPERCLIP_AGENT_ID",
        "PAPERCLIP_COMPANY_ID", "PAPERCLIP_RUN_ID"]


def main():
    health = scratch.send("GET", "/health")
    node = subprocess.run("node --version", shell=True, capture_output=True, text=True)
    print("Paperclip", health["version"] + ", mode", health["deploymentMode"])
    print("Node.js", node.stdout.strip())
    print("Python", platform.python_version() + ", requests", requests.__version__)
    print(platform.system(), platform.release(), platform.version())

    made, boss = scratch.company("Check what it gets")
    agent = scratch.send("POST", "/companies/" + made["id"] + "/agents",
                         {"name": "Printer", "role": "general", "adapterType": "process",
                          "reportsTo": boss["id"],
                          "adapterConfig": {"command": sys.executable, "args": ["-c", PROGRAM]}})
    run = scratch.send("POST", "/agents/" + agent["id"] + "/heartbeat/invoke", {})
    while run["status"] in ("queued", "running"):
        time.sleep(0.2)
        run = scratch.send("GET", "/heartbeat-runs/" + run["id"])
    names = run["resultJson"]["stdout"].split()
    print(f"Run {run['status']}, started by {run['invocationSource']}.")
    print(len(names), "variables whose names begin with PAPERCLIP_:")
    for name in names:
        print("   ", name, "<- cashier.py reads this one" if name in USED else "")
    missing = [name for name in USED if name not in names]
    print("Missing ones that cashier.py reads:", missing or "none")
    scratch.remove(made)


if __name__ == "__main__":
    main()
