#!/usr/bin/env python3
"""Render ${NAME} placeholders from a strict environment file."""

import argparse
import re
from pathlib import Path


def load_env(path: Path) -> dict[str, str]:
    values = {}
    for line in path.read_text(encoding="utf-8").splitlines():
        if not line or line.startswith("#"):
            continue
        key, sep, value = line.partition("=")
        if not sep or not re.fullmatch(r"[A-Z][A-Z0-9_]*", key):
            raise ValueError(f"invalid env line in {path}")
        values[key] = value
    return values


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--env", type=Path, required=True)
    parser.add_argument("--template", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    values = load_env(args.env)
    text = args.template.read_text(encoding="utf-8")
    missing = set()

    def replace(match: re.Match[str]) -> str:
        key = match.group(1)
        value = values.get(key, "")
        if not value or value.startswith(("REQUIRED", "TODO", "CHANGE_ME")):
            missing.add(key)
            return match.group(0)
        return value

    rendered = re.sub(r"\$\{([A-Z][A-Z0-9_]*)\}", replace, text)
    if missing:
        raise ValueError("missing template values: " + ", ".join(sorted(missing)))
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(rendered, encoding="utf-8")
    return 0


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

