#!/usr/bin/env python3
"""Render Kubernetes Secret keys to a mode-0600 env file."""

from __future__ import annotations

import argparse
import os
from pathlib import Path

import yaml


KEYS = {
    "POSTGRES_PASSWORD": "postgresPassword",
    "REDIS_PASSWORD": "redisPassword",
    "MINIO_ROOT_USER": "minioRootUser",
    "MINIO_ROOT_PASSWORD": "minioRootPassword",
    "ARTIFACT_INSTALLER_TOKEN": "artifactInstallerToken",
    "UAV_ACCESS_INTERNAL_TOKEN": "uavAccessInternalToken",
    "FLIGHTHUB_EVENT_CALLBACK_TOKEN": "flighthubEventCallbackToken",
    "EMQX_DASHBOARD_USERNAME": "emqxDashboardUsername",
    "EMQX_DASHBOARD_PASSWORD": "emqxDashboardPassword",
    "FLIGHTHUB_USER_TOKEN": "flighthubUserToken",
    "FLIGHTHUB_MQTT_USERNAME": "flighthubMqttUsername",
    "FLIGHTHUB_MQTT_PASSWORD": "flighthubMqttPassword",
}


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--secrets", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()

    document = yaml.safe_load(args.secrets.read_text(encoding="utf-8"))
    application = document.get("application", {})
    lines: list[str] = []
    for output_key, input_key in KEYS.items():
        value = application.get(input_key, "")
        if not isinstance(value, str) or "\n" in value or "\r" in value:
            raise ValueError(f"secret {input_key} must be a single-line string")
        lines.append(f"{output_key}={value}")

    descriptor = os.open(args.output, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as output:
        output.write("\n".join(lines))
        output.write("\n")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
