#!/usr/bin/env python3
"""Add an isolated MySQL staging credential to the private task file."""

import json
import os

from create_private_credentials import TARGET, password


def main() -> None:
    values = json.loads(TARGET.read_text(encoding="utf-8"))
    if "SOURCE_MYSQL" in values:
        raise SystemExit("Staging credential already exists; refusing to replace it")
    values["SOURCE_MYSQL"] = {"user": "dm_import_ro", "password": password(), "port": 33306}
    temporary = TARGET.with_suffix(".tmp")
    fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
        json.dump(values, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
    os.replace(temporary, TARGET)
    print("Added isolated MySQL credential; content withheld")


if __name__ == "__main__":
    main()
