"""Run against the dedicated, fresh kind cluster after applying configmap.yaml."""
import json
import os
import subprocess
import time
from datetime import datetime, timezone

def kubectl(*args):
    return subprocess.check_output(["kubectl", "-n", "cm-lab", *args], text=True).strip()

def stamp(message):
    print(datetime.now(timezone.utc).isoformat(timespec="milliseconds"), message, flush=True)

def ready_pod():
    pods = json.loads(kubectl("get", "pod", "-l", "app=reader", "-o", "json"))["items"]
    ready = [p for p in pods if not p["metadata"].get("deletionTimestamp")
             and any(c["type"] == "Ready" and c["status"] == "True" for c in p["status"]["conditions"])]
    assert len(ready) == 1
    return ready[0]["metadata"]["name"]

def identity(pod):
    data = json.loads(kubectl("get", "pod", pod, "-o", "json"))
    uid = data["metadata"]["uid"]
    container = data["status"]["containerStatuses"][0]
    stamp(f"pod={pod} uid={uid} restarts={container['restartCount']} imageID={container['imageID']}")
    assert container["restartCount"] == 0
    return uid

def values(pod):
    return kubectl("exec", pod, "--", "sh", "-ec",
                   'printf "env=%s dir=%s subPath=%s" "$MODE" "$(cat /config/mode)" "$(cat /single-mode)"')

def config_version(config):
    return f"cmUID={config['metadata']['uid']} rv={config['metadata']['resourceVersion']} mode={config['data']['mode']}"

assert os.environ.get("KUBECONFIG") and kubectl("config", "current-context") == "kind-cxykk-cm-xbverh"
version = json.loads(kubectl("version", "-o", "json"))
stamp(f"kubectl={version['clientVersion']['gitVersion']} server={version['serverVersion']['gitVersion']}")
node = json.loads(kubectl("get", "nodes", "-o", "json"))["items"][0]["metadata"]["name"]
conf = json.loads(kubectl("get", "--raw", f"/api/v1/nodes/{node}/proxy/configz"))["kubeletconfig"]
stamp(f"syncFrequency={conf['syncFrequency']} changeDetection={conf['configMapAndSecretChangeDetectionStrategy']}")
old = ready_pod()
old_uid = identity(old)
initial = json.loads(kubectl("get", "cm", "settings", "-o", "json"))
stamp(config_version(initial))
before = values(old)
stamp("before " + before)
assert before == "env=v1 dir=v1 subPath=v1"
changed = json.loads(kubectl("patch", "cm", "settings", "--type", "merge", "-p", '{"data":{"mode":"v2"}}', "-o", "json"))
start = time.monotonic()
stamp("patch acknowledged " + config_version(changed))
assert initial["metadata"]["uid"] == changed["metadata"]["uid"] and initial["metadata"]["resourceVersion"] != changed["metadata"]["resourceVersion"]
while time.monotonic() - start < 180:
    reading = values(old)
    elapsed = time.monotonic() - start
    stamp(f"elapsed={elapsed:.2f}s {reading}")
    if reading == "env=v1 dir=v2 subPath=v1":
        break
    assert reading == before
    time.sleep(1)
else:
    raise TimeoutError("directory update not observed in 180s")
assert identity(old) == old_uid
stamp(kubectl("rollout", "restart", "deployment/reader"))
stamp(kubectl("rollout", "status", "deployment/reader", "--timeout=120s"))
new = ready_pod()
assert identity(new) != old_uid
after = values(new)
stamp("replacement " + after)
assert after == "env=v2 dir=v2 subPath=v2"
