import argparse
from pathlib import Path


NAS_ENV_OVERRIDES = {
    "CCDI_DB_HOST": "192.168.0.111",
    "CCDI_DB_PORT": "40628",
}


def parse_args():
    parser = argparse.ArgumentParser(description="Render NAS deployment .env for CCDI docker compose.")
    parser.add_argument("--template", required=True)
    parser.add_argument("--output", required=True)
    return parser.parse_args()


def render_env_text(template_text: str) -> str:
    rendered_lines = []
    replaced_keys = set()

    for line in template_text.splitlines():
        key, separator, value = line.partition("=")
        if separator and key in NAS_ENV_OVERRIDES:
            rendered_lines.append(f"{key}={NAS_ENV_OVERRIDES[key]}")
            replaced_keys.add(key)
            continue
        rendered_lines.append(line)

    for key, value in NAS_ENV_OVERRIDES.items():
        if key not in replaced_keys:
            rendered_lines.append(f"{key}={value}")

    return "\n".join(rendered_lines) + "\n"


def main():
    args = parse_args()
    template_path = Path(args.template)
    output_path = Path(args.output)

    template_text = template_path.read_text(encoding="utf-8")
    output_path.write_text(render_env_text(template_text), encoding="utf-8")


if __name__ == "__main__":
    main()
