#!/usr/bin/env python3

from pathlib import Path


def repo_root() -> Path:
    for path in Path(__file__).resolve().parents:
        if (path / "clusters").is_dir() and (path / "services").is_dir():
            return path
    raise RuntimeError("could not locate repository root")  # pragma: no cover


def indent(text: str, spaces: int) -> str:
    prefix = " " * spaces
    return "".join(prefix + line if line.strip("\n") else line for line in text.splitlines(keepends=True))


def main() -> None:
    root = repo_root()
    source = root / "scripts" / "sync" / "monitoring_postmark_exporter.py"
    target = root / "services" / "monitoring" / "postmark-exporter-script.yaml"

    payload = source.read_text(encoding="utf-8")
    if not payload.endswith("\n"):
        payload += "\n"

    yaml = (
        f"# services/monitoring/postmark-exporter-script.yaml\n"
        f"apiVersion: v1\n"
        f"kind: ConfigMap\n"
        f"metadata:\n"
        f"  name: postmark-exporter-script\n"
        f"data:\n"
        f"  monitoring_postmark_exporter.py: |\n"
        f"{indent(payload, 4)}"
    )

    target.write_text(yaml, encoding="utf-8")


if __name__ == "__main__":
    main()
