#!/usr/bin/env python3

# This is mock RMS script; not very functional ...
import json
import os
import sys
import time
from pathlib import Path
from typing import Any

config: dict[str, Any] = {"exit_status": 0}
if os.path.isfile("action.json"):
    with open("action.json", encoding="utf-8") as f:
        config = json.load(f)


def write_target_file(target_file: str | Path) -> None:
    with open(target_file, "w") as f:
        f.write(f"this is the target file {time.time()}\n")


if "target_file" in config:
    target_file = config["target_file"]
    if os.path.isfile(target_file):
        mtime: float | None = os.path.getmtime(target_file)
    else:
        mtime = None

    write_target_file(target_file)

    # Try to ensure that mtime is updated for target file
    base_sleep_time = 1
    for sleep_pow in range(5):
        if mtime is not None and mtime == os.path.getmtime(target_file):
            time.sleep(base_sleep_time * 2**sleep_pow)
            write_target_file(target_file)
            time.sleep(base_sleep_time * 2**sleep_pow)
        else:
            break


with open("env.json", "w") as f:
    env = {}
    for key in (
        "LM_LICENSE_FILE",
        "PATH",
        "PYTHONPATH",
        "RMS_PLUGINS_LIBRARY",
        "RMS_TEST_VAR",
        "RUNRMS_EXEC_MODE",
        "_PRE_RMS_BACKUP",
        "_PRE_RMS_PYTHONPATH",
    ):
        if key in os.environ:
            env[key] = os.environ[key]

    json.dump(env, f)

sys.exit(config["exit_status"])
