#!/usr/bin/env python3
import os
import sys

try:
    import yaml
except Exception:
    print("Missing dependency: pyyaml", file=sys.stderr)
    raise

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CHART_DIR = os.path.join(ROOT, "charts", "agentarea")
CONFIG_PATH = os.path.join(CHART_DIR, "config.yaml")
OUTPUT_DIR = os.path.join(CHART_DIR, "templates", "configs")


def ensure_output_dir():
    os.makedirs(OUTPUT_DIR, exist_ok=True)


def quote_if_needed(val: str) -> str:
    if val is None:
        return '""'
    s = str(val)
    
    # If the value is a Helm template expression starting with {{ and ending with }},
    # we want to preserve it exactly as is, but ensure the result is quoted for YAML safety if needed.
    # However, the user specifically wants `DBNAME: {{ .Values... | quote }}` structure for some fields.
    # The previous manual fix used `quote` pipeline within the template.
    
    if s.startswith('"') and s.endswith('"'):
        return s
    
    # Check if it looks like a Helm template
    if "{{" in s and "}}" in s:
        # If it's a simple template substitution, wrap in quotes to be safe string
        # unless it already has the quote pipeline
        if "| quote" in s:
             return s
        return f'"{s}"'
        
    return f'"{s}"'


def render_config_vars(group_name: str, cfg: dict) -> str:
    lines = []
    lines.append(f'{{{{- define "agentarea.{group_name}.configVars" -}}}}')
    for k, v in (cfg.get("configVars") or {}).items():
        lines.append(f"{k}: {quote_if_needed(v)}")
    lines.append("{{- end }}")
    return "\n".join(lines)


def _sanitize_group(name: str) -> str:
    return ''.join(c.lower() if c.isalnum() else '-' for c in name)


def render_envs(group_name: str, cfg: dict) -> str:
    cm = f"{{{{ include \"agentarea.fullname\" . }}}}-env-{_sanitize_group(group_name)}"
    lines = []
    lines.append(f'{{{{- define "agentarea.{group_name}.envs" }}}}')
    for k in (cfg.get("configVars") or {}).keys():
        lines.extend([
            f"- name: {k}",
            "  valueFrom:",
            "    configMapKeyRef:",
            f"      name: {cm}",
            f"      key: {k}",
        ])
    for extra in (cfg.get("envExtras") or []):
        lines.extend([
            f"- name: {extra.get('name')}",
            f"  value: {extra.get('value')}",
        ])
    lines.append("{{- end }}")
    return "\n".join(lines)


def render_secrets_envs(group_name: str, cfg: dict) -> str | None:
    secrets = cfg.get("secrets") or []
    if not secrets:
        return None
    conditional = cfg.get("conditional")
    lines = []
    lines.append(f'{{{{- define "agentarea.{group_name}.secrets.envs" }}}}')
    if conditional:
        cond = conditional.replace('{{', '').replace('}}', '').strip()
        lines.append(f"{{{{ if {cond} }}}}")
    for sec in secrets:
        name = sec.get("name")
        if "value" in sec and sec["value"] is not None:
            lines.extend([
                f"- name: {name}",
                f"  value: {sec['value']}",
            ])
        else:
            lines.extend([
                f"- name: {name}",
                "  valueFrom:",
                "    secretKeyRef:",
                f"      name: {quote_if_needed(sec.get('secretName'))}",
                f"      key: {sec.get('key')}",
            ])
    if conditional:
        lines.append("{{- end }}")
    lines.append("{{- end }}")
    return "\n".join(lines)


def generate_group_tpl(name: str, group_cfg: dict) -> str:
    header = (
        "{{/*\n"
        "AUTOGENERATED FILE - DO NOT EDIT.\n"
        "Generated by scripts/generate_env_tpls.py from charts/agentarea/config.yaml\n"
        "*/}}\n\n"
    )
    sections = [render_config_vars(name, group_cfg), "", render_envs(name, group_cfg)]
    secrets_block = render_secrets_envs(name, group_cfg)
    if secrets_block:
        sections.extend(["", secrets_block])
    return header + "\n".join(sections) + "\n"


def main():
    ensure_output_dir()
    with open(CONFIG_PATH, "r", encoding="utf-8") as f:
        raw = f.read()
    cfg = yaml.safe_load(raw)
    groups = cfg.get("groups") or {}
    for name, group_cfg in groups.items():
        out_path = os.path.join(OUTPUT_DIR, f"{name.replace('-', '_')}.env.tpl")
        content = generate_group_tpl(name, group_cfg or {})
        os.makedirs(os.path.dirname(out_path), exist_ok=True)
        with open(out_path, "w", encoding="utf-8") as f:
            f.write(content)
    print(f"Generated env tpls for groups: {', '.join(sorted(groups.keys()))}")


if __name__ == "__main__":
    main()
