import copy
import json
import logging
import os
import subprocess
import tempfile
import time
import urllib.request

client_logger = logging.getLogger("kion-federation-client")
server_logger = logging.getLogger("kion-federation-server")


def client(proxy_url: str):
    client_logger.info(f"Getting kion federation URL from {proxy_url}")
    with urllib.request.urlopen(proxy_url) as resp:  # nosec: B310
        args = json.loads(resp.read().decode())
        client_logger.debug(f"Running open {' '.join(args)}")
        subprocess.call(["open"] + args)


def server(favourite: str, kion_bin: str):
    server_logger.info(f"Getting federation URL for {favourite}")
    env = copy.deepcopy(os.environ)
    my_directory = os.path.dirname(env["LOGIN_AUTH_BINARY"])
    server_logger.debug(f"Prepending {my_directory} to PATH")
    new_path = f"{my_directory}:{env['PATH']}"
    env["PATH"] = new_path

    with tempfile.NamedTemporaryFile("r") as tmpf:
        env["OPEN_PROXY_OUTPUT"] = tmpf.name
        server_logger.debug(f"Open args will be written to {tmpf.name}")

        try:
            subprocess.check_call(
                [kion_bin, "favorite", "-w", favourite], stdout=subprocess.PIPE, env=env
            )
        except Exception:
            server_logger.exception("kion failed")
            raise Exception("Kion failed to federate")

        time.sleep(3)  # Needed to let the filesystem figure things out

        args = json.load(tmpf)
        return args
