#!/usr/bin/env python3
"""
Gem nuværende vandingsindstillinger som nye 'initial' standardværdier i YAML-filerne.
Efter dette script køres vil næste HA-genstart bruge de gemte værdier.

Køres inde i homeassistant Docker-containeren via shell_command.
"""
import re
import json
import urllib.request

DATETIME_FILE = "/config/include/input/datetime/vanding.yaml"
NUMBER_FILE   = "/config/include/input/number/vanding.yaml"
SECRETS_FILE  = "/config/secrets.yaml"
HA_URL        = "http://localhost:8123"

DATETIME_ENTITIES = [
    "vanding_morgen_tid",
    "vanding_aften_tid",
    "vanding_sikkerhedsstop_morgen",
    "vanding_sikkerhedsstop_nat",
]

NUMBER_ENTITIES = [
    "vanding_varighed_smart",
    "vanding_varighed_hojbed_1",
    "vanding_varighed_hojbed_2",
    "vanding_varighed_hojbed_3",
]


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, timeout=10) as resp:
        return {d["entity_id"]: d["state"] for d in json.loads(resp.read())}


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)
    saved = []

    # Gem input_datetime tider
    with open(DATETIME_FILE) as f:
        dt_content = f.read()

    for name in DATETIME_ENTITIES:
        entity_id = f"input_datetime.{name}"
        state = states.get(entity_id)
        if state in (None, "unavailable", "unknown"):
            print(f"  SPRING OVER {entity_id}: {state}")
            continue
        # HA returnerer HH:MM:SS for input_datetime (time only)
        dt_content = update_initial(dt_content, name, state)
        saved.append(f"{entity_id} = {state}")

    with open(DATETIME_FILE, "w") as f:
        f.write(dt_content)

    # Gem input_number værdier
    with open(NUMBER_FILE) as f:
        num_content = f.read()

    for name in NUMBER_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 = float(state)
        val_str = str(int(val)) if val == int(val) else str(val)
        # input_number initial er uden anførselstegn
        pattern = rf"(^{re.escape(name)}:\n(?:  [^\n]*\n)*?  initial: )\S+"
        num_content, count = re.subn(
            pattern, rf"\g<1>{val_str}", num_content, flags=re.MULTILINE, count=1
        )
        if count == 0:
            print(f"  ADVARSEL: {name} ikke fundet i YAML")
        else:
            saved.append(f"{entity_id} = {val_str}")

    with open(NUMBER_FILE, "w") as f:
        f.write(num_content)

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


if __name__ == "__main__":
    main()

