#!/usr/bin/env python3
"""Print shell-safe `KEY=value` lines for one instance from instances.yaml.

Used by scripts/ha/import.sh via:
  eval "$(python3 lib/instance_config.py instances.yaml <name>)"
"""
import shlex
import sys

import yaml

FIELDS = [
    "host",
    "container",
    "config_mount",
    "adapter",
    "base_url",
    "token_path",
    "status",
    "site",
]


def main(argv):
    if len(argv) != 3:
        print("usage: instance_config.py <instances.yaml> <instance-name>", file=sys.stderr)
        return 2
    instances_path, name = argv[1], argv[2]
    with open(instances_path, "r", encoding="utf-8") as f:
        data = yaml.safe_load(f)
    instances = (data or {}).get("instances", {})
    if name not in instances:
        known = ", ".join(sorted(instances)) or "(none)"
        print(f"unknown instance '{name}' (known: {known})", file=sys.stderr)
        return 1
    inst = instances[name] or {}
    ssh = inst.get("ssh") or {}
    print(f"HA_INSTANCE={shlex.quote(name)}")
    for field in FIELDS:
        print(f"HA_{field.upper()}={shlex.quote(str(inst.get(field, '')))}")
    print(f"HA_SSH_USER={shlex.quote(str(ssh.get('user', '')))}")
    print(f"HA_SSH_HOST={shlex.quote(str(ssh.get('host', '')))}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
