#!/usr/bin/env python3
"""
Gem nuværende varme-indstillinger som nye 'initial' standardværdier i YAML-filen.
Køres inde i homeassistant Docker-containeren.
"""
import re
import json
import urllib.request

YAML_FILE    = "/config/include/input/number/varme.yaml"
SECRETS_FILE = "/config/secrets.yaml"
HA_URL       = "http://localhost:8123"

ENTITIES = [
    "varme_komfort_andreas",
    "varme_komfort_daniel",
    "varme_komfort_sovevaerelse",
    "varme_komfort_kontor",
    "varme_komfort_gang",
    "varme_komfort_forgang",
    "varme_komfort_lille_bad",
    "varme_komfort_badevarelse",
    "varme_komfort_stue",
    "varme_komfort_bryggers",
    "varme_komfort_kokken",
    "varme_nat_saenkning",
    "varme_vaek_saenkning",
    "varme_ferie_temp",
]


def get_token():
    with open(SECRETS_FILE) as f:
        for line in f:
            if line.startswith("ha_token:"):
                return line.split(":", 1)[1].strip()
    raise ValueError("ha_token ikke fundet i secrets.yaml")


def get_states(token):
    req = urllib.request.Request(
        f"{HA_URL}/api/states",
        headers={"Authorization": f"Bearer {token}"},
    )
    with urllib.request.urlopen(req) as resp:
        return {d["entity_id"]: d["state"] for d in json.loads(resp.read())}


def format_value(state_str):
    val = float(state_str)
    return str(int(val)) if val == int(val) else str(val)


def update_initial(content, entity_name, new_value):
    """Erstat initial-værdien for en given entity i YAML-indholdet."""
    pattern = rf"(^{re.escape(entity_name)}:\n(?:  [^\n]*\n)*?  initial: )\S+"
    new_content, count = re.subn(
        pattern, rf"\g<1>{new_value}", content, flags=re.MULTILINE, count=1
    )
    if count == 0:
        print(f"  ADVARSEL: {entity_name} ikke fundet i YAML")
    return new_content


def main():
    token = get_token()
    states = get_states(token)

    with open(YAML_FILE) as f:
        content = f.read()

    saved = []
    for name in ENTITIES:
        entity_id = f"input_number.{name}"
        state = states.get(entity_id)
        if state in (None, "unavailable", "unknown"):
            print(f"  SPRING OVER {entity_id}: {state}")
            continue
        val_str = format_value(state)
        content = update_initial(content, name, val_str)
        saved.append(f"{entity_id} = {val_str}")

    with open(YAML_FILE, "w") as f:
        f.write(content)

    print(f"Gemt {len(saved)} standardværdier -> {YAML_FILE}")
    for line in saved:
        print(f"  {line}")


if __name__ == "__main__":
    main()
