#!/usr/bin/env python3
"""Render Helm overrides derived from a validated site configuration."""

from __future__ import annotations

import argparse
import copy
import os
import re
from pathlib import Path

import yaml

DIGEST_PATTERN = re.compile(r"^sha256:[0-9a-f]{64}$")


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

    site = yaml.safe_load(args.site.read_text(encoding="utf-8"))
    versions = yaml.safe_load(args.versions.read_text(encoding="utf-8"))
    raw_values = site.get("helmValues")
    if not isinstance(raw_values, dict):
        raise ValueError("site configuration is missing helmValues")

    values = copy.deepcopy(raw_values)
    deployment = site["deployment"]
    storage = site["storage"]
    gpu = site["gpu"]

    values.setdefault("global", {})
    values["global"]["runtimeProfile"] = deployment["runtimeProfile"]
    values["global"]["storageClass"] = storage["storageClass"]
    values["modelStorage"] = {
        "capacity": storage["modelCapacity"],
        "accessMode": storage["modelAccessMode"],
    }
    values.setdefault("gpu", {})
    values["gpu"]["enabled"] = gpu["enabled"]
    values.setdefault("images", {})
    for name, locked_image in versions.get("images", {}).items():
        digest = locked_image.get("digest", "") if isinstance(locked_image, dict) else ""
        if DIGEST_PATTERN.fullmatch(str(digest)):
            values["images"].setdefault(name, {})
            values["images"][name]["digest"] = digest

    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:
        yaml.safe_dump(values, output, allow_unicode=True, sort_keys=False)
    return 0


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