// Package greencell is a built-in connector for Greencell EV charging stations —
// today the HabuDen wallbox (11/22 kW, 32 A), the one device Greencell itself
// supports for third-party integration.
//
// There is no Greencell cloud API to talk to. The charger is commissioned over
// Bluetooth in the Greencell GC app, where the owner points it at an MQTT broker
// of their own and switches the "Home Assistant" integration on; from then on the
// wallbox publishes its telemetry to that broker. This connector is therefore an
// MQTT client, not an HTTP one: it joins the same broker and reads the topics the
// device publishes. The wire contract is the one Home Assistant's own greencell
// integration speaks (homeassistant/components/greencell, and the greencell_client
// 1.0.3 library it builds on), which is the only published description of it:
//
//	publish  /greencell/broadcast          {"name":"BROADCAST"}  — ask devices to announce
//	subscribe /greencell/broadcast/device  {"id":"<serial>", …}  — a device announcing itself
//	subscribe /greencell/evse/<sn>/current      {"l1":…,"l2":…,"l3":…}  milliamps
//	subscribe /greencell/evse/<sn>/voltage      {"l1":…,"l2":…,"l3":…}  volts
//	subscribe /greencell/evse/<sn>/power        {"momentary":…}         watts
//	subscribe /greencell/evse/<sn>/status       {"state":"CHARGING"}
//	subscribe /greencell/evse/<sn>/device_state {"level":"EXECUTE"}     access level
//
// Scope & limitations:
//   - Read-only. The GC app can put a device in EXECUTE mode, in which it accepts
//     START / STOP / SET_CURRENT / QUERY commands — but the topic those commands
//     are published on is documented nowhere: not in Greencell's integration page,
//     not in greencell_client, and Home Assistant's own integration ships without
//     control for exactly that reason. The access level is reported (CanExecute)
//     so the UI can say what the device would allow; acting on it needs that
//     topic, which is the one missing piece. An operator who has found theirs can
//     set commandTopic, and a state read will then send QUERY (the one command a
//     READ-mode device also honours) to prompt an immediate publish.
//   - Local, not cloud. The broker is the owner's; nothing here reaches Greencell.
//     The charger and this server must both be able to reach it.
//   - Pull-shaped over a push protocol. The plugin contract builds an instance per
//     call, so each Invoke opens a short-lived session, asks for a broadcast, reads
//     what arrives within a bounded window, and disconnects. It does not hold a
//     subscription open between calls, so a reading is as fresh as the device's own
//     publish cadence within that window.
//   - HabuDen. Serials matching the HabuDen pattern are named as such; any other
//     Greencell device that speaks these topics is still read, just generically.
package greencell

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"

	"drivervault/apiserver/internal/mqtt"
	"drivervault/apiserver/internal/plugins"
)

// Topics. The leading slash is part of the contract — Greencell publishes on
// absolute topics, not the relative ones MQTT conventions would suggest.
const (
	broadcastTopic = "/greencell/broadcast"
	discoveryTopic = "/greencell/broadcast/device"
	evsePrefix     = "/greencell/evse/"
)

// Per-device topic suffixes, which double as the keys of the raw/received maps.
const (
	topicCurrent     = "current"
	topicVoltage     = "voltage"
	topicPower       = "power"
	topicStatus      = "status"
	topicDeviceState = "device_state"
)

// telemetryTopics are the per-device suffixes a state read subscribes to.
var telemetryTopics = []string{topicCurrent, topicVoltage, topicPower, topicStatus, topicDeviceState}

// Device naming, mirroring the upstream integration.
const (
	nameHabuDen = "Habu Den"
	nameGeneric = "Greencell Device"
)

// habuDenSerial matches a HabuDen serial (greencell_client GreencellUtils).
var habuDenSerial = regexp.MustCompile(`^EVGC021[A-Z][0-9]{8}ZM[0-9]{4}$`)

// EVSE states the device reports on the status topic, lowercased. Anything the
// device sends that is not in this set is reported as stateUnknown rather than
// passed through, so a consumer can switch on a closed set.
const (
	stateIdle          = "idle"
	stateConnected     = "connected"
	stateWaitingForCar = "waiting_for_car"
	stateCharging      = "charging"
	stateFinished      = "finished"
	stateErrorCar      = "error_car"
	stateErrorEVSE     = "error_evse"
	stateUnavailable   = "unavailable"
	stateUnknown       = "unknown"
)

var evseStates = map[string]bool{
	stateIdle: true, stateConnected: true, stateWaitingForCar: true,
	stateCharging: true, stateFinished: true, stateErrorCar: true,
	stateErrorEVSE: true, stateUnavailable: true,
}

// Access levels the device reports on device_state — the mode chosen in the GC
// app. OFFLINE is the deprecated spelling of UNAVAILABLE and is folded into it,
// as greencell_client does.
const (
	accessDisabled    = "disabled"
	accessRead        = "read"
	accessExecute     = "execute"
	accessUnavailable = "unavailable"
	accessUnknown     = "unknown"
)

// Broker defaults. 1883 is plain MQTT, 8883 the TLS port.
const (
	defaultPort    = "1883"
	defaultTLSPort = "8883"
)

// Collection window bounds. A device answers a broadcast within 30 s per
// Greencell's own troubleshooting note, but that is far too long to hold an HTTP
// request open, so the default is shorter and the operator can raise it.
const (
	defaultTimeout = 12 * time.Second
	minTimeout     = 1 * time.Second
	maxTimeout     = 60 * time.Second
	// discoveryGrace is how much longer discovery listens after the first device
	// replies, to catch the rest of a multi-charger site. Upstream uses the same
	// half second.
	discoveryGrace = 500 * time.Millisecond
)

func init() {
	plugins.Register("greencell", func() plugins.Plugin { return &Plugin{} })
}

// snPlaceholder is substituted with the charger serial in a configured command
// topic, so one setting can serve every charger on a broker.
const snPlaceholder = "{sn}"

// queryCommand is the payload that asks a device to publish its state at once.
// Greencell documents QUERY as honoured in both READ and EXECUTE mode; what it
// does not document is the topic to send it on, hence commandTopic being an
// operator-supplied opt-in.
const queryCommand = "QUERY"

// Plugin is the Greencell EVSE connector.
type Plugin struct {
	mu           sync.Mutex // guards the config below; Invoke may run concurrently
	address      string
	useTLS       bool
	username     string
	password     string
	serial       string
	commandTopic string
	timeout      time.Duration
}

// Descriptor returns the plugin's static metadata for the admin panel.
func (p *Plugin) Descriptor() plugins.Descriptor {
	return plugins.Descriptor{
		Name:     "greencell",
		Provider: "Greencell (HabuDen EV charger)",
		Version:  "1.0.0",
		Kind:     plugins.KindBuiltin,
		Category: plugins.CategoryChargers,
		AuthType: plugins.AuthBasic,
		Capabilities: []plugins.Capability{
			{ID: "chargers", Method: "SUB", Endpoint: discoveryTopic,
				Description: "Discover Greencell chargers on the broker by publishing a broadcast and collecting the announcements."},
			{ID: "charger-state", Method: "SUB", Endpoint: evsePrefix + "{sn}/#",
				Description: "Normalized live state of one charger: EVSE status, access level, power, per-phase current and voltage (needs sn, or the configured serial)."},
		},
		ConfigFields: []plugins.ConfigField{
			// As with the Toyota and Anker connectors, nothing is Required at the
			// global layer: an operator may configure a shared broker here or leave
			// it to the per-user cascade. Missing values surface as a clear error
			// when a call is actually made.
			{Key: "host", Label: "MQTT broker host", Type: "text",
				Help: "Hostname or IP of the MQTT broker the charger was pointed at in the Greencell GC app (for example 10.2.1.10)."},
			{Key: "port", Label: "MQTT broker port", Type: "number", Default: defaultPort,
				Help: "Broker TCP port. Defaults to 1883, or 8883 when TLS is on."},
			{Key: "tls", Label: "Use TLS", Type: "select", Default: "off",
				Help: "Connect to the broker over TLS. Must match how the broker is configured.",
				Options: []plugins.SelectOption{
					{Value: "off", Label: "Off (plain MQTT)"},
					{Value: "on", Label: "On (MQTTS)"},
				}},
			{Key: "username", Label: "MQTT username", Type: "text",
				Help: "Broker username, if the broker requires authentication. Leave blank for an open broker."},
			{Key: "password", Label: "MQTT password", Type: "password", Secret: true,
				Help: "Broker password for the username above."},
			{Key: "serial", Label: "Charger serial", Type: "text",
				Help: "Serial of the charger, e.g. EVGC021B22752405ZM0018. Optional — leave blank and discovery will find whatever is on the broker."},
			{Key: "commandTopic", Label: "QUERY command topic", Type: "text",
				Help: "Optional. Greencell documents a QUERY command that makes the charger publish its state immediately, but not the topic to send it on — no published source names it. If you find yours (watch your broker while the GC app talks to the charger), put it here and reads stop waiting for the device's own cadence. Use " + snPlaceholder + " for the serial, e.g. /greencell/evse/" + snPlaceholder + "/command. Leave blank to listen only."},
			{Key: "timeout", Label: "Listen window (seconds)", Type: "number", Default: "12",
				Help: "How long to wait for the charger to publish before answering. Greencell allows a device up to 30 s to respond to a broadcast; raise this if discovery comes back empty."},
		},
	}
}

// Init applies resolved config. It performs no network I/O — every call opens its
// own short-lived broker session.
func (p *Plugin) Init(_ context.Context, config map[string]string) error {
	p.mu.Lock()
	defer p.mu.Unlock()

	p.useTLS = truthy(config["tls"])
	host := strings.TrimSpace(config["host"])
	port := strings.TrimSpace(config["port"])
	if port == "" {
		port = defaultPort
		if p.useTLS {
			port = defaultTLSPort
		}
	}
	p.address = ""
	if host != "" {
		p.address = net.JoinHostPort(host, port)
	}
	p.username = strings.TrimSpace(config["username"])
	p.password = config["password"]
	p.serial = strings.TrimSpace(config["serial"])
	p.commandTopic = strings.TrimSpace(config["commandTopic"])
	p.timeout = parseTimeout(config["timeout"])
	return nil
}

// HealthCheck connects to the broker and asks whatever is listening to announce
// itself. A reachable broker with no charger on it is degraded rather than down:
// the half we configure works, and the missing half is the device.
func (p *Plugin) HealthCheck(ctx context.Context) plugins.Health {
	start := time.Now()
	found, err := p.discover(ctx)
	lat := time.Since(start).Milliseconds()
	if err != nil {
		return plugins.Health{Status: plugins.StatusDown, LatencyMs: lat, Detail: shorten(err.Error())}
	}
	if len(found) == 0 {
		return plugins.Health{Status: plugins.StatusDegraded, LatencyMs: lat,
			Detail: "broker reachable, but no Greencell device answered the discovery broadcast"}
	}
	return plugins.Health{Status: plugins.StatusOK, LatencyMs: lat,
		Detail: fmt.Sprintf("broker reachable; %d Greencell device(s) answered", len(found))}
}

// invokeParams is what an action may be given. Per-charger actions take "sn"; it
// falls back to the configured serial when omitted.
type invokeParams struct {
	SN string `json:"sn"`
}

// Invoke runs a named read-only capability.
func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessage) (json.RawMessage, error) {
	var pp invokeParams
	if len(params) > 0 {
		if err := json.Unmarshal(params, &pp); err != nil {
			return nil, fmt.Errorf("greencell: invalid params: %w", err)
		}
	}
	sn := strings.TrimSpace(pp.SN)
	if sn == "" {
		sn = p.configuredSerial()
	}

	switch action {
	case "chargers":
		found, err := p.discover(ctx)
		if err != nil {
			return nil, err
		}
		return json.Marshal(map[string]any{"chargers": found})
	case "charger-state":
		if sn == "" {
			return nil, errors.New("greencell: action \"charger-state\" requires an sn (charger serial), or a serial in the plugin config")
		}
		st, err := p.chargerState(ctx, sn)
		if err != nil {
			return nil, err
		}
		return json.Marshal(st)
	default:
		return nil, fmt.Errorf("greencell: unknown action %q", action)
	}
}

// Shutdown has nothing to release: sessions do not outlive a call.
func (p *Plugin) Shutdown(context.Context) error { return nil }

// ---- broker session ----------------------------------------------------------

// snapshot copies the config under the lock so a call is not affected by a
// concurrent Init.
func (p *Plugin) snapshot() (opts mqtt.Options, timeout time.Duration, err error) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if p.address == "" {
		return mqtt.Options{}, 0, errors.New("greencell: no MQTT broker configured — set the broker host the charger publishes to")
	}
	return mqtt.Options{
		Address:  p.address,
		TLS:      p.useTLS,
		Username: p.username,
		Password: p.password,
		// One keep-alive period comfortably outlives a listen window, so the
		// session never has to ping mid-collection.
		Keepalive:      60 * time.Second,
		ConnectTimeout: 10 * time.Second,
	}, p.timeout, nil
}

func (p *Plugin) configuredSerial() string {
	p.mu.Lock()
	defer p.mu.Unlock()
	return p.serial
}

// commandTopicFor resolves the configured QUERY topic for one charger, or ""
// when the operator has not supplied one.
func (p *Plugin) commandTopicFor(sn string) string {
	p.mu.Lock()
	defer p.mu.Unlock()
	if p.commandTopic == "" {
		return ""
	}
	return strings.ReplaceAll(p.commandTopic, snPlaceholder, sn)
}

// session opens a broker connection, subscribes to topics, and publishes the
// discovery broadcast that prompts devices to speak up. The caller drains
// client.Messages until it has what it came for or its window runs out, then
// closes the client.
func (p *Plugin) session(ctx context.Context, topics []string) (*mqtt.Client, time.Duration, error) {
	opts, timeout, err := p.snapshot()
	if err != nil {
		return nil, 0, err
	}
	client, err := mqtt.Connect(ctx, opts)
	if err != nil {
		return nil, 0, err
	}
	if err := client.Subscribe(ctx, topics...); err != nil {
		_ = client.Close()
		return nil, 0, fmt.Errorf("greencell: subscribing on the broker: %w", err)
	}
	// The broadcast is what makes an otherwise-quiet device announce itself; the
	// telemetry topics then follow on the device's own cadence.
	if err := client.Publish(ctx, broadcastTopic, []byte(`{"name":"BROADCAST"}`)); err != nil {
		_ = client.Close()
		return nil, 0, fmt.Errorf("greencell: publishing the discovery broadcast: %w", err)
	}
	return client, timeout, nil
}

// ---- discovery ---------------------------------------------------------------

// Device is one charger that answered the discovery broadcast.
type Device struct {
	SN    string `json:"sn"`
	Name  string `json:"name"`
	Model string `json:"model"`
	// Announcement is the device's own broadcast payload, passed through
	// unchanged: Greencell may carry firmware or capability fields there that
	// this connector has no schema for.
	Announcement json.RawMessage `json:"announcement,omitempty"`
}

// discover collects the devices that answer a broadcast. It listens for the full
// window, cut short by discoveryGrace once at least one device has replied.
func (p *Plugin) discover(ctx context.Context) ([]Device, error) {
	client, timeout, err := p.session(ctx, []string{discoveryTopic})
	if err != nil {
		return nil, err
	}
	defer client.Close()

	found := map[string]Device{}
	var order []string

	deadline := time.NewTimer(timeout)
	defer deadline.Stop()
	var grace *time.Timer
	graceC := func() <-chan time.Time {
		if grace == nil {
			return nil
		}
		return grace.C
	}

	for {
		select {
		case msg, ok := <-client.Messages():
			if !ok {
				if err := client.Err(); err != nil {
					return nil, err
				}
				return devicesInOrder(found, order), nil
			}
			if msg.Topic != discoveryTopic {
				continue
			}
			dev, ok := parseAnnouncement(msg.Payload)
			if !ok {
				continue
			}
			if _, seen := found[dev.SN]; !seen {
				order = append(order, dev.SN)
			}
			found[dev.SN] = dev
			if grace == nil {
				grace = time.NewTimer(discoveryGrace)
				defer grace.Stop()
			}
		case <-graceC():
			return devicesInOrder(found, order), nil
		case <-deadline.C:
			return devicesInOrder(found, order), nil
		case <-ctx.Done():
			return nil, ctx.Err()
		}
	}
}

// devicesInOrder returns the collected devices in the order they answered.
func devicesInOrder(found map[string]Device, order []string) []Device {
	out := make([]Device, 0, len(order))
	for _, sn := range order {
		out = append(out, found[sn])
	}
	return out
}

// parseAnnouncement reads a device announcement. A payload without a usable "id"
// is not a device and is ignored.
func parseAnnouncement(payload []byte) (Device, bool) {
	var doc struct {
		ID string `json:"id"`
	}
	if err := json.Unmarshal(payload, &doc); err != nil {
		return Device{}, false
	}
	sn := strings.TrimSpace(doc.ID)
	if sn == "" {
		return Device{}, false
	}
	model := deviceModel(sn)
	return Device{
		SN:           sn,
		Name:         model + " " + sn,
		Model:        model,
		Announcement: json.RawMessage(append([]byte(nil), payload...)),
	}, true
}

// deviceModel names a device from its serial.
func deviceModel(sn string) string {
	if habuDenSerial.MatchString(sn) {
		return nameHabuDen
	}
	return nameGeneric
}

// ---- live state --------------------------------------------------------------

// Phases holds a per-phase measurement. A phase the device did not report stays
// nil rather than reading as zero, which on a charger would be a real value.
type Phases struct {
	L1 *float64 `json:"l1"`
	L2 *float64 `json:"l2"`
	L3 *float64 `json:"l3"`
}

// State is one charger's normalized live state.
type State struct {
	SN    string `json:"sn"`
	Name  string `json:"name"`
	Model string `json:"model"`

	// Status is the EVSE state, lowercased and constrained to the known set.
	Status   string `json:"status"`
	Charging bool   `json:"charging"`
	// Plugged is true in every state that implies a cable in the socket.
	Plugged bool `json:"plugged"`
	// Fault is true for the two error states.
	Fault bool `json:"fault"`

	// AccessLevel is the integration mode set in the Greencell GC app, and
	// CanExecute is whether that mode would accept commands. Control is not
	// implemented (see the package comment); this reports what the device allows.
	AccessLevel string `json:"accessLevel"`
	CanExecute  bool   `json:"canExecute"`
	Available   bool   `json:"available"`

	PowerW   *float64 `json:"powerW"`
	CurrentA Phases   `json:"currentA"`
	VoltageV Phases   `json:"voltageV"`
	// LivePhases counts the phases currently drawing a meaningful current, which
	// is what separates a 1-phase from a 3-phase charge on a 22 kW wallbox.
	LivePhases int `json:"livePhases"`

	// Received says which topics were heard inside the listen window; a false
	// entry means that field is unset, not zero.
	Received map[string]bool `json:"received"`
	// Raw is each topic's last payload, verbatim, for fields this connector has
	// no schema for.
	Raw        map[string]json.RawMessage `json:"raw,omitempty"`
	ObservedAt time.Time                  `json:"observedAt"`
	// Complete is true when every telemetry topic reported inside the window.
	Complete bool `json:"complete"`
}

// chargerState listens for one charger's telemetry and normalizes it. It returns
// as soon as every topic has been heard, or at the end of the window with
// whatever arrived — a device that publishes some topics on a slower cadence
// still yields a useful partial reading, flagged by Received/Complete. Total
// silence is an error: that means the charger is not on this broker.
func (p *Plugin) chargerState(ctx context.Context, sn string) (State, error) {
	topics := make([]string, 0, len(telemetryTopics)+1)
	topics = append(topics, discoveryTopic)
	for _, suffix := range telemetryTopics {
		topics = append(topics, evsePrefix+sn+"/"+suffix)
	}

	client, timeout, err := p.session(ctx, topics)
	if err != nil {
		return State{}, err
	}
	defer client.Close()

	// When the operator has told us where the charger listens, ask it to publish
	// now rather than waiting out its own cadence. A device in DISABLE or READ
	// mode ignores every other command but this one, so it is safe to send
	// whatever mode the charger is in. Failing to publish is not fatal: the
	// listen-only path still works.
	if topic := p.commandTopicFor(sn); topic != "" {
		_ = client.Publish(ctx, topic, []byte(queryCommand))
	}

	raw := map[string]json.RawMessage{}
	deadline := time.NewTimer(timeout)
	defer deadline.Stop()

collect:
	for len(raw) < len(telemetryTopics) {
		select {
		case msg, ok := <-client.Messages():
			if !ok {
				if err := client.Err(); err != nil {
					return State{}, err
				}
				break collect
			}
			if suffix, match := topicSuffix(msg.Topic, sn); match && json.Valid(msg.Payload) {
				raw[suffix] = json.RawMessage(append([]byte(nil), msg.Payload...))
			}
		case <-deadline.C:
			break collect
		case <-ctx.Done():
			return State{}, ctx.Err()
		}
	}

	if len(raw) == 0 {
		return State{}, fmt.Errorf("greencell: no data from charger %s within %s — check that it is powered, on this broker, and not set to DISABLE in the GC app", sn, timeout)
	}
	return buildState(sn, raw), nil
}

// topicSuffix maps a received topic back to its per-device suffix.
func topicSuffix(topic, sn string) (string, bool) {
	prefix := evsePrefix + sn + "/"
	if !strings.HasPrefix(topic, prefix) {
		return "", false
	}
	suffix := strings.TrimPrefix(topic, prefix)
	for _, known := range telemetryTopics {
		if suffix == known {
			return suffix, true
		}
	}
	return "", false
}

// buildState turns the collected payloads into a normalized reading.
func buildState(sn string, raw map[string]json.RawMessage) State {
	model := deviceModel(sn)
	st := State{
		SN:          sn,
		Name:        model + " " + sn,
		Model:       model,
		Status:      stateUnknown,
		AccessLevel: accessUnknown,
		Received:    map[string]bool{},
		Raw:         raw,
		ObservedAt:  time.Now().UTC(),
	}
	for _, suffix := range telemetryTopics {
		st.Received[suffix] = raw[suffix] != nil
	}
	st.Complete = len(raw) == len(telemetryTopics)

	// Current arrives in milliamps; every other consumer wants amperes.
	st.CurrentA = scalePhases(parsePhases(raw[topicCurrent]), 1.0/1000.0)
	st.VoltageV = parsePhases(raw[topicVoltage])
	st.PowerW = numberField(raw[topicPower], "momentary")

	if s, ok := stringField(raw[topicStatus], "state"); ok {
		st.Status = normalizeState(s)
	}
	// The device also signals unavailability through the status topic itself,
	// which upstream detects by substring because the payload is not a state
	// document in that case.
	if isUnavailable(raw[topicStatus]) {
		st.Status = stateUnavailable
	}

	if s, ok := stringField(raw[topicDeviceState], "level"); ok {
		st.AccessLevel = normalizeAccess(s)
	}
	st.CanExecute = st.AccessLevel == accessExecute
	st.Available = st.AccessLevel != accessDisabled && st.AccessLevel != accessUnavailable &&
		st.Status != stateUnavailable

	st.Charging = st.Status == stateCharging
	switch st.Status {
	case stateConnected, stateWaitingForCar, stateCharging, stateFinished, stateErrorCar:
		st.Plugged = true
	}
	st.Fault = st.Status == stateErrorCar || st.Status == stateErrorEVSE
	st.LivePhases = countLivePhases(st.CurrentA)
	return st
}

// livePhaseThreshold is the current above which a phase counts as carrying a
// charge, in amperes. Greencell's own floor for a charging session is 6 A, so
// anything under an amp is measurement noise on an idle phase.
const livePhaseThreshold = 1.0

func countLivePhases(p Phases) int {
	n := 0
	for _, v := range []*float64{p.L1, p.L2, p.L3} {
		if v != nil && *v >= livePhaseThreshold {
			n++
		}
	}
	return n
}

// normalizeState constrains a reported EVSE state to the known set.
func normalizeState(s string) string {
	v := strings.ToLower(strings.TrimSpace(s))
	if evseStates[v] {
		return v
	}
	return stateUnknown
}

// normalizeAccess maps a reported access level to the known set, folding the
// deprecated OFFLINE into UNAVAILABLE as greencell_client does.
func normalizeAccess(s string) string {
	switch strings.ToLower(strings.TrimSpace(s)) {
	case "execute":
		return accessExecute
	case "read":
		return accessRead
	case "disabled", "disable":
		return accessDisabled
	case "offline", "unavailable":
		return accessUnavailable
	default:
		return accessUnknown
	}
}

// isUnavailable reports whether a status payload is one of the out-of-band
// unavailability markers rather than a state document.
func isUnavailable(payload json.RawMessage) bool {
	if payload == nil {
		return false
	}
	up := strings.ToUpper(string(payload))
	return strings.Contains(up, "UNAVAILABLE") || strings.Contains(up, "OFFLINE")
}

// ---- payload parsing ---------------------------------------------------------

// parsePhases reads an {"l1":…,"l2":…,"l3":…} payload. A phase that is absent or
// not a number stays nil — the device is documented to send numbers, and a
// non-numeric value is better reported as missing than coerced to zero.
func parsePhases(payload json.RawMessage) Phases {
	if payload == nil {
		return Phases{}
	}
	var doc map[string]json.RawMessage
	if err := json.Unmarshal(payload, &doc); err != nil {
		return Phases{}
	}
	return Phases{L1: asNumber(doc["l1"]), L2: asNumber(doc["l2"]), L3: asNumber(doc["l3"])}
}

// scalePhases multiplies every present phase by factor.
func scalePhases(p Phases, factor float64) Phases {
	scale := func(v *float64) *float64 {
		if v == nil {
			return nil
		}
		out := *v * factor
		return &out
	}
	return Phases{L1: scale(p.L1), L2: scale(p.L2), L3: scale(p.L3)}
}

// numberField reads one numeric field out of a payload.
func numberField(payload json.RawMessage, key string) *float64 {
	if payload == nil {
		return nil
	}
	var doc map[string]json.RawMessage
	if err := json.Unmarshal(payload, &doc); err != nil {
		return nil
	}
	return asNumber(doc[key])
}

// stringField reads one string field out of a payload.
func stringField(payload json.RawMessage, key string) (string, bool) {
	if payload == nil {
		return "", false
	}
	var doc map[string]json.RawMessage
	if err := json.Unmarshal(payload, &doc); err != nil {
		return "", false
	}
	var s string
	if err := json.Unmarshal(doc[key], &s); err != nil {
		return "", false
	}
	return s, true
}

// asNumber decodes a JSON number, also accepting one quoted as a string, which
// some firmware revisions do.
func asNumber(raw json.RawMessage) *float64 {
	if len(raw) == 0 {
		return nil
	}
	// json.Unmarshal accepts null into a float64 and leaves it at zero, which on a
	// charger is a real reading; an explicit null means "no value".
	if string(raw) == "null" {
		return nil
	}
	var f float64
	if err := json.Unmarshal(raw, &f); err == nil {
		return &f
	}
	var s string
	if err := json.Unmarshal(raw, &s); err != nil {
		return nil
	}
	f, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
	if err != nil {
		return nil
	}
	return &f
}

// ---- config helpers ----------------------------------------------------------

// truthy reads a boolean-ish config value; the panel writes selects as strings.
func truthy(v string) bool {
	switch strings.ToLower(strings.TrimSpace(v)) {
	case "on", "true", "yes", "1", "tls", "mqtts":
		return true
	default:
		return false
	}
}

// parseTimeout reads the listen window in seconds, clamped to a range that keeps
// an HTTP request honest at one end and useful at the other.
func parseTimeout(v string) time.Duration {
	n, err := strconv.Atoi(strings.TrimSpace(v))
	if err != nil || n <= 0 {
		return defaultTimeout
	}
	d := time.Duration(n) * time.Second
	return max(minTimeout, min(d, maxTimeout))
}

// shorten trims a message to something a health detail can carry.
func shorten(s string) string {
	const limit = 200
	s = strings.TrimSpace(s)
	if len(s) <= limit {
		return s
	}
	return s[:limit] + "…"
}
