#!/usr/bin/env python3
"""Sends the per-zone Wi-Fi counts that Checkmk already holds to Occupi.

Runs on the Checkmk server as the site user, from cron. It reads the aggregate performance
data of one service (default "Users per Floor") from the local Checkmk, and makes one outbound
HTTPS call to Occupi. It never talks to a Wi-Fi controller and never opens a listening port.

Python 3 standard library only. See README.md in this folder.

History: `--backfill FROM TO` reads the service's RRD history from Checkmk itself and writes a
CSV file for the Wi-Fi page's "Counts from a file" import. It never sends old readings to Occupi
(the ingest refuses readings over 35 days old) and needs no Occupi address or key.

Exit codes
  0  done (readings sent, or nothing to send)
  2  settings problem (nothing was read or sent)
  3  Checkmk could not be read (a held backlog is still sent)
  4  Occupi could not be reached or refused a batch (readings are kept for the next run)
  5  Occupi rejected the collector key (readings are kept)
"""
from __future__ import annotations

import argparse
import concurrent.futures
import configparser
import csv
import fcntl
import json
import logging
import logging.handlers
import math
import os
import re
import shutil
import socket
import ssl
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter
from datetime import datetime, timedelta, timezone
from typing import Any, Callable, Dict, List, Optional, Tuple

VERSION = "1.1"

EXIT_OK = 0
EXIT_CONFIG = 2
EXIT_READ = 3
EXIT_SEND = 4
EXIT_KEY = 5

SLOT_SECONDS = 15 * 60
BACKFILL_DAYS = 35
CLOCK_SKEW_SECONDS = 5 * 60
MAX_DEVICES_PER_AP = 5000
CHUNK_SIZE = 2000  # the server accepts 5000 per request and 1 MB; this stays well inside both

LOG = logging.getLogger("occupi-push")


class ConfigError(Exception):
    pass


class ReadError(Exception):
    pass


# ---------------------------------------------------------------------------------------------
# Perf data parsing: a port of src/lib/wifi/checkmk.ts and apIdFrom in src/lib/wifi/cells.ts.
# Keep these in step with the TypeScript; test_occupi_checkmk_push.py holds the shared cases.
# ---------------------------------------------------------------------------------------------

# JavaScript's \s and trim(), spelled out so Python and JavaScript agree on what is whitespace.
_JS_SPACE = " \t\n\v\f\r      　﻿" + "".join(chr(c) for c in range(0x2000, 0x200B))
_WS = re.escape(_JS_SPACE)

# One metric: a name (single-quoted when it has spaces, '' for a quote), "=", a number with an
# optional unit, then warn;crit;min;max, which don't matter here.
_METRIC = re.compile(
    r"('(?:[^']|'')+'|[^" + _WS + r"=']+)=(-?[0-9.]+)[^" + _WS + r";]*(?:;[^" + _WS + r"]*)?"
)


def js_round(value: float) -> int:
    """Math.round: halves go up. (Python's round() goes to the even number.)"""
    return int(math.floor(value + 0.5))


def parse_metrics(perf_data: str) -> List[Tuple[str, Optional[int]]]:
    """Every metric as (name, count). The count is None when it isn't a usable number."""
    out: List[Tuple[str, Optional[int]]] = []
    for match in _METRIC.finditer(perf_data):
        raw_name = match.group(1)
        name = raw_name[1:-1].replace("''", "'") if raw_name.startswith("'") else raw_name
        try:
            value = float(match.group(2))
        except ValueError:
            value = float("nan")
        usable = math.isfinite(value) and value >= 0
        out.append((name, js_round(value) if usable else None))
    return out


_PLACEHOLDER = re.compile(r"(n/?a|none|null|wired|unknown|-)", re.ASCII | re.IGNORECASE)


def ap_id_from(value: str) -> str:
    """An access point or zone name as an id the ingest accepts; empty when there's nothing to go on."""
    trimmed = value.strip(_JS_SPACE)
    cleaned = re.sub(r"[^A-Za-z0-9._:-]+", "-", trimmed)
    cleaned = re.sub(r"-{2,}", "-", cleaned)
    cleaned = cleaned.strip("-")[:64]
    if not re.search(r"[A-Za-z0-9]", cleaned):
        return ""
    return "" if _PLACEHOLDER.fullmatch(trimmed) else cleaned


def counts_from_services(rows: List[Dict[str, str]]) -> Dict[str, int]:
    """Zone id -> count for the service rows ({host, service, perf_data}), as the CSV import reads them."""
    parsed = [(row["host"], parse_metrics(row.get("perf_data", ""))) for row in rows]
    with_metrics = [(host, metrics) for host, metrics in parsed if metrics]
    if not with_metrics:
        return {}
    # One service per access point, each with a single "clients" metric: the host is the zone.
    host_is_zone = len(with_metrics) > 1 and all(len(metrics) == 1 for _, metrics in with_metrics)
    counts: Dict[str, int] = {}
    for host, metrics in with_metrics:
        for name, value in metrics:
            if value is None:
                continue
            zone = ap_id_from(host if host_is_zone else name)
            if not zone:
                continue
            # Two services naming the same zone (two controllers) add up.
            counts[zone] = counts.get(zone, 0) + value
    return counts


# ---------------------------------------------------------------------------------------------
# Settings
# ---------------------------------------------------------------------------------------------


def site_home() -> str:
    return os.environ.get("OMD_ROOT") or os.path.expanduser("~")


class Settings:
    def __init__(self, values: Dict[str, str]):
        self.v = values

    def get(self, key: str, default: str = "") -> str:
        return self.v.get(key, default)

    @property
    def url(self) -> str:
        return self.get("url").rstrip("/")


_DEFAULTS = {
    "service": "Users per Floor",
    "host": "",
    "source": "livestatus",
    "timeout": "20",
    "spool_max": "20000",
    "lq_command": "",
    "socket": "",
    "rest_url": "",
    "rest_creds_file": "",
    "rest_verify_tls": "yes",
    "rest_ca_file": "",
    "timezone": "",
}

_ENV = {
    "url": "OCCUPI_URL",
    "key_file": "OCCUPI_KEY_FILE",
    "service": "OCCUPI_SERVICE",
    "host": "OCCUPI_HOST",
    "source": "OCCUPI_SOURCE",
    "timeout": "OCCUPI_TIMEOUT",
    "spool_max": "OCCUPI_SPOOL_MAX",
    "state_dir": "OCCUPI_STATE_DIR",
    "log_file": "OCCUPI_LOG_FILE",
    "lq_command": "OCCUPI_LQ_COMMAND",
    "socket": "OCCUPI_LIVESTATUS_SOCKET",
    "rest_url": "OCCUPI_REST_URL",
    "rest_creds_file": "OCCUPI_REST_CREDS_FILE",
    "rest_verify_tls": "OCCUPI_REST_VERIFY_TLS",
    "rest_ca_file": "OCCUPI_REST_CA_FILE",
    "timezone": "OCCUPI_TIMEZONE",
}

_PATH_KEYS = ("key_file", "state_dir", "log_file", "socket", "rest_creds_file", "rest_ca_file", "lq_command")


def load_settings(path: Optional[str], environ: Dict[str, str], require_occupi: bool = True) -> Settings:
    home = site_home()
    values: Dict[str, str] = dict(_DEFAULTS)
    values["state_dir"] = os.path.join(home, "var", "occupi-push")
    values["log_file"] = os.path.join(home, "var", "log", "occupi-push.log")
    config_path = path or environ.get("OCCUPI_CONFIG") or os.path.join(home, "etc", "occupi-push.ini")
    if os.path.exists(config_path):
        parser = configparser.ConfigParser(interpolation=None)
        try:
            parser.read(config_path, encoding="utf-8")
        except configparser.Error as err:
            raise ConfigError("Could not read %s: %s" % (config_path, err))
        for section in parser.sections():
            for key, value in parser.items(section):
                values[key] = value.strip()
    elif path:
        raise ConfigError("Settings file not found: %s" % path)
    for key, env_name in _ENV.items():
        if environ.get(env_name):
            values[key] = environ[env_name]
    for key in _PATH_KEYS:
        if values.get(key):
            values[key] = os.path.expanduser(values[key])
    return validate(Settings(values), require_occupi)


def validate(settings: Settings, require_occupi: bool = True) -> Settings:
    if not require_occupi:
        return validate_checkmk(settings)
    if not settings.url:
        raise ConfigError("No Occupi address. Set url in the settings file (for example https://occupi.example.ac.uk).")
    parsed = urllib.parse.urlparse(settings.url)
    if parsed.scheme not in ("https", "http") or not parsed.hostname:
        raise ConfigError("The Occupi address must look like https://host.")
    if parsed.scheme == "http" and parsed.hostname not in ("localhost", "127.0.0.1", "::1"):
        raise ConfigError("The Occupi address must be https. Plain http is only allowed for localhost.")
    if not settings.get("key_file"):
        raise ConfigError("No collector key file. Set key_file in the settings file.")
    return validate_checkmk(settings)


def validate_checkmk(settings: Settings) -> Settings:
    if settings.get("source") not in ("livestatus", "rest"):
        raise ConfigError("source must be livestatus or rest.")
    if not settings.get("service").strip():
        raise ConfigError("service must not be empty.")
    for label in ("service", "host"):
        if re.search(r"[\n\r\\]", settings.get(label)):
            raise ConfigError("%s must not contain a new line or a backslash." % label)
    for key in ("timeout", "spool_max"):
        try:
            if float(settings.get(key)) <= 0:
                raise ValueError
        except ValueError:
            raise ConfigError("%s must be a positive number." % key)
    if settings.get("source") == "rest" and (not settings.get("rest_url") or not settings.get("rest_creds_file")):
        raise ConfigError("The REST source needs rest_url and rest_creds_file.")
    return settings


def read_secret_file(path: str, what: str) -> str:
    """The first line of a file only its owner may read."""
    try:
        info = os.stat(path)
    except OSError as err:
        raise ConfigError("Cannot read the %s at %s: %s" % (what, path, err.strerror))
    if info.st_mode & 0o077:
        raise ConfigError("The %s at %s can be read by other users. Run: chmod 600 %s" % (what, path, path))
    with open(path, "r", encoding="utf-8") as handle:
        first = handle.readline().strip()
    if not first:
        raise ConfigError("The %s at %s is empty." % (what, path))
    return first


# ---------------------------------------------------------------------------------------------
# Reading Checkmk. Only the aggregate perf data of the configured service is requested.
# ---------------------------------------------------------------------------------------------

LIVESTATUS_COLUMNS = ("host_name", "description", "perf_data")


def livestatus_query(service: str, host: str) -> str:
    lines = ["GET services", "Columns: " + " ".join(LIVESTATUS_COLUMNS), "Filter: description = " + service]
    if host:
        lines.append("Filter: host_name = " + host)
    lines.append("OutputFormat: json")
    return "\n".join(lines)


def _rows_from_livestatus_json(text: str) -> List[Dict[str, str]]:
    try:
        table = json.loads(text) if text.strip() else []
    except ValueError:
        raise ReadError("Livestatus answered with something that is not JSON: %r" % text[:120])
    if not isinstance(table, list):
        raise ReadError("Livestatus answered with an unexpected shape.")
    rows = []
    for item in table:
        if not isinstance(item, list) or len(item) != len(LIVESTATUS_COLUMNS):
            raise ReadError("Livestatus returned a row with the wrong columns.")
        rows.append({"host": str(item[0]), "service": str(item[1]), "perf_data": str(item[2] or "")})
    return rows


def livestatus_text(settings: Settings, query: str, timeout: float) -> str:
    """Runs one Livestatus query (through lq, or the site's socket) and returns the answer."""
    lq = settings.get("lq_command")
    sock_path = settings.get("socket") or os.path.join(site_home(), "tmp", "run", "live")
    if not lq and not settings.get("socket") and shutil.which("lq"):
        lq = "lq"
    if lq:
        try:
            done = subprocess.run([lq, query], capture_output=True, text=True, timeout=timeout)
        except (OSError, subprocess.TimeoutExpired) as err:
            raise ReadError("Could not run %s: %s" % (lq, err))
        if done.returncode != 0:
            raise ReadError("%s failed (%d): %s" % (lq, done.returncode, done.stderr.strip()[:200]))
        return done.stdout
    if not os.path.exists(sock_path):
        raise ReadError("No lq command on the PATH and no Livestatus socket at %s. Run this as the Checkmk site user." % sock_path)
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
            sock.settimeout(timeout)
            sock.connect(sock_path)
            sock.sendall((query + "\n\n").encode("utf-8"))
            chunks = []
            while True:
                data = sock.recv(65536)
                if not data:
                    break
                chunks.append(data)
    except OSError as err:
        raise ReadError("Could not read the Livestatus socket %s: %s" % (sock_path, err))
    return b"".join(chunks).decode("utf-8", "replace")


def read_livestatus(settings: Settings, timeout: float) -> List[Dict[str, str]]:
    query = livestatus_query(settings.get("service"), settings.get("host"))
    return _rows_from_livestatus_json(livestatus_text(settings, query, timeout))


def rest_request_url(base: str, service: str, host: str) -> str:
    """<base>/check_mk/api/1.0/domain-types/service/collections/all with columns and a Livestatus-style filter."""
    expr: List[Dict[str, str]] = [{"op": "=", "left": "description", "right": service}]
    if host:
        expr.append({"op": "=", "left": "host_name", "right": host})
    query = json.dumps({"op": "and", "expr": expr}, separators=(",", ":"))
    params = [("columns", c) for c in LIVESTATUS_COLUMNS] + [("query", query)]
    return base.rstrip("/") + "/check_mk/api/1.0/domain-types/service/collections/all?" + urllib.parse.urlencode(params)


def parse_rest_services(body: Any) -> List[Dict[str, str]]:
    members = body.get("value") if isinstance(body, dict) else None
    if not isinstance(members, list):
        raise ReadError("The Checkmk REST API answered with an unexpected shape.")
    rows = []
    for member in members:
        ext = member.get("extensions") if isinstance(member, dict) else None
        if not isinstance(ext, dict):
            continue
        perf = ext.get("perf_data", "")
        if isinstance(perf, list):
            perf = " ".join(str(p) for p in perf)
        rows.append({"host": str(ext.get("host_name", "")), "service": str(ext.get("description", "")), "perf_data": str(perf or "")})
    return rows


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args: Any, **kwargs: Any) -> None:
        return None


def _opener(context: Optional[ssl.SSLContext] = None) -> urllib.request.OpenerDirector:
    handlers: List[Any] = [_NoRedirect()]
    if context is not None:
        handlers.append(urllib.request.HTTPSHandler(context=context))
    return urllib.request.build_opener(*handlers)


def read_rest(settings: Settings, timeout: float) -> List[Dict[str, str]]:
    creds = read_secret_file(settings.get("rest_creds_file"), "REST credentials file")
    parts = creds.split(None, 1)
    if len(parts) != 2:
        raise ConfigError("The REST credentials file must hold the automation user name and its secret on one line, separated by a space.")
    user, secret = parts[0], parts[1].strip()
    url = rest_request_url(settings.get("rest_url"), settings.get("service"), settings.get("host"))
    request = urllib.request.Request(
        url,
        headers={"Authorization": "Bearer %s %s" % (user, secret), "Accept": "application/json", "User-Agent": "occupi-checkmk-push/" + VERSION},
    )
    context = None
    if url.startswith("https://"):
        if settings.get("rest_verify_tls").lower() in ("no", "false", "0"):
            context = ssl._create_unverified_context()  # for the site's own self-signed certificate on localhost
        else:
            context = ssl.create_default_context(cafile=settings.get("rest_ca_file") or None)
    try:
        with _opener(context).open(request, timeout=timeout) as response:
            body = json.loads(response.read().decode("utf-8"))
    except urllib.error.HTTPError as err:
        raise ReadError("The Checkmk REST API refused the request: HTTP %d" % err.code)
    except (urllib.error.URLError, OSError, ValueError) as err:
        raise ReadError("Could not read the Checkmk REST API: %s" % err)
    return parse_rest_services(body)


def read_checkmk(settings: Settings) -> List[Dict[str, str]]:
    timeout = float(settings.get("timeout"))
    return read_rest(settings, timeout) if settings.get("source") == "rest" else read_livestatus(settings, timeout)


# ---------------------------------------------------------------------------------------------
# Readings, spool and sending
# ---------------------------------------------------------------------------------------------


def slot_start(epoch_seconds: float) -> int:
    return int(epoch_seconds // SLOT_SECONDS) * SLOT_SECONDS


def iso_utc(ts: int) -> str:
    return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def build_readings(counts: Dict[str, int], now: float) -> Tuple[List[Dict[str, Any]], List[str]]:
    """One reading per zone for the current 15-minute slot. Zones the server would reject are left out."""
    ts = slot_start(now)
    readings: List[Dict[str, Any]] = []
    skipped: List[str] = []
    for zone in sorted(counts):
        if counts[zone] > MAX_DEVICES_PER_AP:
            skipped.append(zone)
            continue
        readings.append({"apId": zone, "ts": ts, "deviceCount": counts[zone]})
    return readings, skipped


def merge_readings(held: List[Dict[str, Any]], fresh: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    """Held and fresh readings, one per zone and slot (the fresher wins), oldest first."""
    merged: Dict[Tuple[str, int], Dict[str, Any]] = {}
    for reading in held + fresh:
        merged[(reading["apId"], reading["ts"])] = reading
    return sorted(merged.values(), key=lambda r: (r["ts"], r["apId"]))


def within_window(readings: List[Dict[str, Any]], now: float) -> Tuple[List[Dict[str, Any]], int]:
    """Readings Occupi would accept. One outside its window fails the whole request, so they are dropped here."""
    earliest = now - BACKFILL_DAYS * 86400 + 3600
    latest = now + CLOCK_SKEW_SECONDS
    kept = [r for r in readings if earliest <= r["ts"] <= latest]
    return kept, len(readings) - len(kept)


def cap_spool(readings: List[Dict[str, Any]], limit: int) -> Tuple[List[Dict[str, Any]], int]:
    if len(readings) <= limit:
        return readings, 0
    return readings[len(readings) - limit :], len(readings) - limit


def load_spool(path: str) -> List[Dict[str, Any]]:
    try:
        with open(path, "r", encoding="utf-8") as handle:
            data = json.load(handle)
    except FileNotFoundError:
        return []
    except (OSError, ValueError):
        LOG.warning("The held-readings file %s could not be read and was set aside.", path)
        try:
            os.replace(path, path + ".bad")
        except OSError:
            pass
        return []
    good = []
    for item in data if isinstance(data, list) else []:
        if (
            isinstance(item, dict)
            and isinstance(item.get("apId"), str)
            and isinstance(item.get("ts"), int)
            and isinstance(item.get("deviceCount"), int)
        ):
            good.append({"apId": item["apId"], "ts": item["ts"], "deviceCount": item["deviceCount"]})
    return good


def save_spool(path: str, readings: List[Dict[str, Any]]) -> None:
    if not readings:
        try:
            os.remove(path)
        except FileNotFoundError:
            pass
        return
    tmp = path + ".tmp"
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
        json.dump(readings, handle, separators=(",", ":"))
    os.replace(tmp, path)


def payload_for(readings: List[Dict[str, Any]]) -> Dict[str, Any]:
    return {"readings": [{"apId": r["apId"], "ts": iso_utc(r["ts"]), "deviceCount": r["deviceCount"]} for r in readings]}


class SendResult:
    def __init__(self, kind: str, detail: str = ""):
        self.kind = kind  # ok | retry | key | rejected
        self.detail = detail


def post_batch(base_url: str, key: str, readings: List[Dict[str, Any]], timeout: float) -> SendResult:
    body = json.dumps(payload_for(readings)).encode("utf-8")
    request = urllib.request.Request(
        base_url + "/api/ingest",
        data=body,
        method="POST",
        headers={"Authorization": "Bearer " + key, "Content-Type": "application/json", "User-Agent": "occupi-checkmk-push/" + VERSION},
    )
    try:
        with _opener().open(request, timeout=timeout) as response:
            return SendResult("ok", response.read().decode("utf-8", "replace"))
    except urllib.error.HTTPError as err:
        text = err.read().decode("utf-8", "replace")[:300]
        if err.code in (401, 403):
            return SendResult("key", "HTTP %d" % err.code)
        if err.code in (400, 413, 422):
            return SendResult("rejected", "HTTP %d: %s" % (err.code, text))
        return SendResult("retry", "HTTP %d: %s" % (err.code, text))
    except (urllib.error.URLError, OSError) as err:
        return SendResult("retry", str(getattr(err, "reason", err)))


def send_all(
    settings: Settings,
    key: str,
    readings: List[Dict[str, Any]],
    on_acknowledged: Callable[[List[Dict[str, Any]]], None],
) -> Tuple[int, List[Dict[str, Any]], int]:
    """Sends in batches. Returns (exit code, readings still to send, readings sent).

    on_acknowledged(remaining) runs after each accepted batch, so nothing acknowledged is sent twice.
    """
    timeout = float(settings.get("timeout"))
    remaining = list(readings)
    sent = 0
    code = EXIT_OK
    while remaining:
        batch = remaining[:CHUNK_SIZE]
        result = post_batch(settings.url, key, batch, timeout)
        if result.kind == "ok":
            remaining = remaining[len(batch) :]
            sent += len(batch)
            on_acknowledged(remaining)
            continue
        if result.kind == "rejected":
            # The same batch would be refused every time, so it is dropped rather than blocking all later ones.
            LOG.error("Occupi refused a batch of %d readings and it was dropped: %s", len(batch), result.detail)
            remaining = remaining[len(batch) :]
            on_acknowledged(remaining)
            code = EXIT_SEND
            continue
        if result.kind == "key":
            LOG.error("Occupi did not accept the collector key (%s). Make a new key on the Occupi Setup page. Readings are kept.", result.detail)
            return EXIT_KEY, remaining, sent
        LOG.error("Could not send to Occupi (%s). %d readings are kept for the next run.", result.detail, len(remaining))
        return EXIT_SEND, remaining, sent
    return code, remaining, sent


# ---------------------------------------------------------------------------------------------
# The run
# ---------------------------------------------------------------------------------------------


def setup_logging(path: str, verbose: bool) -> None:
    LOG.setLevel(logging.INFO)
    for old in list(LOG.handlers):
        LOG.removeHandler(old)
        old.close()
    fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        handler: logging.Handler = logging.handlers.RotatingFileHandler(path, maxBytes=512 * 1024, backupCount=3, encoding="utf-8")
        handler.setFormatter(fmt)
        LOG.addHandler(handler)
    except OSError:
        pass
    if verbose or sys.stderr.isatty() or not LOG.handlers:
        console = logging.StreamHandler(sys.stderr)
        console.setFormatter(fmt)
        LOG.addHandler(console)


def run(settings: Settings, dry_run: bool, now: Optional[float] = None, out: Any = None) -> int:
    out = out or sys.stdout
    now = time.time() if now is None else now
    key = read_secret_file(settings.get("key_file"), "collector key file")
    os.makedirs(settings.get("state_dir"), mode=0o700, exist_ok=True)
    spool_path = os.path.join(settings.get("state_dir"), "spool.json")

    read_code = EXIT_OK
    fresh: List[Dict[str, Any]] = []
    try:
        rows = read_checkmk(settings)
        counts = counts_from_services(rows)
        where = " on " + settings.get("host") if settings.get("host") else ""
        if not rows:
            LOG.warning("Checkmk has no service called %r%s.", settings.get("service"), where)
            read_code = EXIT_READ
        elif not counts:
            LOG.warning("The service %r has no usable counts in its performance data.", settings.get("service"))
            read_code = EXIT_READ
        fresh, skipped = build_readings(counts, now)
        for zone in skipped:
            LOG.warning("Zone %s reports more than %d devices and was left out.", zone, MAX_DEVICES_PER_AP)
    except ReadError as err:
        LOG.error("%s", err)
        read_code = EXIT_READ

    held = load_spool(spool_path)
    candidates, dropped_window = within_window(merge_readings(held, fresh), now)
    if dropped_window:
        LOG.warning("Dropped %d held readings that are too old for Occupi to accept.", dropped_window)

    if dry_run:
        report = {"dryRun": True, "url": settings.url + "/api/ingest", "held": len(held), "fresh": len(fresh), **payload_for(candidates)}
        print(json.dumps(report, indent=2), file=out)
        return read_code

    if not candidates:
        save_spool(spool_path, [])
        return read_code

    capped, dropped = cap_spool(candidates, int(float(settings.get("spool_max"))))
    if dropped:
        LOG.warning("The held-readings file is over its limit (%s). Dropped the %d oldest readings.", settings.get("spool_max"), dropped)
    save_spool(spool_path, capped)
    send_code, _remaining, sent = send_all(settings, key, capped, lambda left: save_spool(spool_path, left))
    if send_code == EXIT_OK:
        LOG.info("Sent %d readings (%d zones in this reading).", sent, len(fresh))
    elif sent:
        LOG.info("Sent %d readings before stopping.", sent)
    return send_code if send_code != EXIT_OK else read_code


# ---------------------------------------------------------------------------------------------
# History: --backfill FROM TO. Reads the RRD history of the one service and writes a CSV file.
#
# Livestatus (preferred, no credentials; runs as the site user). The services table has a
# dynamic column `rrddata`:
#     rrddata:TITLE:METRIC.average:FROM_TIME:UNTIL_TIME:RESOLUTION
# Its answer is a flat list [start, end, step, value, value, ...]; value n is at start + n * step,
# and a gap is null. RESOLUTION is a minimum: Checkmk returns the RRD's own step when that is
# coarser, and merges values up to RESOLUTION when it is finer. By default the RRDs keep 1 minute
# for 2 days, 5 minutes for 10 days, 30 minutes for 90 days, then 6 hours for four years.
#
# REST API (fallback, needs an automation user): POST <rest_url>/check_mk/api/1.0/
# domain-types/metric/actions/get/invoke with
#     {"type": "single_metric", "host_name": ..., "service_description": ..., "metric_id": ...,
#      "time_range": {"start": ISO, "end": ISO}, "reduce": "average"}
# which answers {"time_range": {"start": ISO, "end": ISO}, "step": N, "metrics": [{"data_points": [...]}]}.
# ---------------------------------------------------------------------------------------------

HISTORY_FORMAT = 1
HISTORY_HEADER = ["zone", "timestamp", "count", "step_seconds"]
HISTORY_MIN_TIMEOUT = 120.0
LIVESTATUS_SPAN_SECONDS = 7 * 86400  # RRD picks its resolution from the start of the range, so ask a week at a time
LIVESTATUS_METRICS_PER_QUERY = 40
REST_SPAN_SECONDS = 31 * 86400
REST_WORKERS = 4
LONG_RANGE_DAYS = 120
LARGE_FILE_BYTES = 20 * 1024 * 1024  # Occupi reads files up to 25 MB

# Livestatus splits a column on ":" and the RPN on ","; its header lines split on spaces.
_LIVESTATUS_UNSAFE = re.compile(r"[\s:,\x00-\x1f]")
_REST_METRIC_ID = re.compile(r"^\w[_\-\w\.]*$", re.ASCII)

Fetched = Dict[Tuple[str, str], Dict[int, Tuple[Optional[float], int]]]
Points = List[Tuple[int, Optional[float], int]]  # (timestamp, value or None for a gap, step in seconds)


class Target:
    """One metric of one host, and the zone its numbers belong to."""

    def __init__(self, host: str, metric: str, zone: str):
        self.host, self.metric, self.zone = host, metric, zone


def history_targets(rows: List[Dict[str, str]]) -> List[Target]:
    """Which metrics to fetch and the zone of each. Mirrors counts_from_services."""
    parsed = [(row["host"], parse_metrics(row.get("perf_data", ""))) for row in rows]
    with_metrics = [(host, metrics) for host, metrics in parsed if metrics]
    host_is_zone = len(with_metrics) > 1 and all(len(metrics) == 1 for _, metrics in with_metrics)
    targets: List[Target] = []
    for host, metrics in with_metrics:
        for name, _value in metrics:
            zone = ap_id_from(host if host_is_zone else name)
            if zone:
                targets.append(Target(host, name, zone))
    return targets


def _zoneinfo(name: str) -> Any:
    try:
        from zoneinfo import ZoneInfo

        return ZoneInfo(name)
    except Exception:
        raise ConfigError("The time zone %r is not known on this server. Use a name such as Europe/London, or leave timezone out to use the server's own." % name)


def parse_when(text: str, tz_name: str, end_of_day: bool = False) -> int:
    """Epoch seconds for a date (campus time, or the server's own), or for an ISO time with its own offset.

    A bare date means its start, or with end_of_day the start of the next day, so that "2026-10-01 2026-10-31"
    covers both days whole.
    """
    raw = text.strip()
    if not raw:
        raise ConfigError("A date is empty. Use YYYY-MM-DD, for example 2026-10-01.")
    spaced = re.sub(r"^(\d{4}-\d{2}-\d{2}) ", r"\1T", raw)
    iso = re.sub(r"[zZ]$", "+00:00", spaced)
    try:
        moment = datetime.fromisoformat(iso)
    except ValueError:
        raise ConfigError("Cannot read the date %r. Use YYYY-MM-DD (for example 2026-10-01) or 2026-10-01T08:00." % text)
    if end_of_day and re.fullmatch(r"\d{4}-\d{2}-\d{2}", raw):
        moment = moment + timedelta(days=1)
    if moment.tzinfo is None:
        if tz_name:
            moment = moment.replace(tzinfo=_zoneinfo(tz_name))
        else:
            moment = moment.astimezone()  # the server's own zone, with its daylight saving
    return int(moment.timestamp())


def resolve_range(start_text: str, end_text: str, tz_name: str, now: float) -> Tuple[int, int]:
    start = parse_when(start_text, tz_name)
    end = min(parse_when(end_text, tz_name, end_of_day=True), int(now))
    if end <= start:
        raise ConfigError("The end date must be after the start date, and not in the future.")
    return start, end


def livestatus_history_query(service: str, host: str, metrics: List[str], start: int, end: int, step: int) -> str:
    lines = ["GET services", "Filter: description = " + service]
    if host:
        lines.append("Filter: host_name = " + host)
    cols = ["rrddata:m%d:%s.average:%d:%d:%d" % (i, name, start, end, step) for i, name in enumerate(metrics)]
    lines.append("Columns: host_name " + " ".join(cols))
    lines.append("OutputFormat: json")
    return "\n".join(lines)


def points_from_rrd(column: Any, start: int, end: int) -> Points:
    """[start, end, step, v0, v1, ...] as points inside [start, end). Empty for 'no such metric'."""
    if not isinstance(column, list) or len(column) < 4:
        return []
    try:
        first, step = int(column[0]), int(column[2])
    except (TypeError, ValueError):
        return []
    if step <= 0:
        return []
    out: Points = []
    for i, raw in enumerate(column[3:]):
        ts = first + i * step
        if ts < start or ts >= end:
            continue
        try:
            value: Optional[float] = None if raw is None else float(raw)
        except (TypeError, ValueError):
            value = None
        if value is not None and not math.isfinite(value):
            value = None
        out.append((ts, value, step))
    return out


def parse_livestatus_history(text: str, metrics: List[str], start: int, end: int) -> Dict[Tuple[str, str], Points]:
    try:
        table = json.loads(text) if text.strip() else []
    except ValueError:
        raise ReadError("Livestatus answered with something that is not JSON: %r" % text[:120])
    if not isinstance(table, list):
        raise ReadError("Livestatus answered with an unexpected shape.")
    found: Dict[Tuple[str, str], Points] = {}
    for item in table:
        if not isinstance(item, list) or len(item) != len(metrics) + 1:
            raise ReadError("Livestatus returned a row with the wrong columns.")
        for name, column in zip(metrics, item[1:]):
            points = points_from_rrd(column, start, end)
            if points:
                found[(str(item[0]), name)] = points
    return found


def merge_points(into: Fetched, key: Tuple[str, str], points: Points) -> None:
    """Adds points; across two requests a real value beats a gap, otherwise the first one stays."""
    series = into.setdefault(key, {})
    for ts, value, step in points:
        have = series.get(ts)
        if have is None or (have[0] is None and value is not None):
            series[ts] = (value, step)


def fetch_history_livestatus(settings: Settings, targets: List[Target], start: int, end: int) -> Fetched:
    timeout = max(float(settings.get("timeout")), HISTORY_MIN_TIMEOUT)
    names = sorted({t.metric for t in targets if not _LIVESTATUS_UNSAFE.search(t.metric)})
    wanted = {(t.host, t.metric) for t in targets}
    out: Fetched = {}
    for chunk_start in range(start, end, LIVESTATUS_SPAN_SECONDS):
        chunk_end = min(chunk_start + LIVESTATUS_SPAN_SECONDS, end)
        for i in range(0, len(names), LIVESTATUS_METRICS_PER_QUERY):
            batch = names[i : i + LIVESTATUS_METRICS_PER_QUERY]
            # 900 s: recent minutes are merged up to 15 minutes; older, coarser RRD steps come back as they are.
            query = livestatus_history_query(settings.get("service"), settings.get("host"), batch, chunk_start, chunk_end, SLOT_SECONDS)
            found = parse_livestatus_history(livestatus_text(settings, query, timeout), batch, chunk_start, chunk_end)
            for key, points in found.items():
                if key in wanted:
                    merge_points(out, key, points)
    return out


def rest_metric_url(base: str) -> str:
    return base.rstrip("/") + "/check_mk/api/1.0/domain-types/metric/actions/get/invoke"


def rest_metric_body(service: str, target: Target, start: int, end: int) -> Dict[str, Any]:
    return {
        "type": "single_metric",
        "host_name": target.host,
        "service_description": service,
        "metric_id": target.metric,
        "time_range": {"start": iso_utc(start), "end": iso_utc(end)},
        "reduce": "average",
    }


def _epoch(value: Any) -> int:
    if isinstance(value, (int, float)):
        return int(value)
    return int(datetime.fromisoformat(re.sub(r"[zZ]$", "+00:00", str(value))).timestamp())


def points_from_rest(body: Any, start: int, end: int) -> Points:
    if not isinstance(body, dict) or not isinstance(body.get("metrics"), list):
        raise ReadError("The Checkmk REST API answered with an unexpected shape.")
    if not body["metrics"]:
        return []
    try:
        first, step = _epoch(body["time_range"]["start"]), int(body["step"])
    except (KeyError, TypeError, ValueError):
        raise ReadError("The Checkmk REST API answered without a time range or step.")
    column: List[Any] = [first, 0, step]
    column.extend(body["metrics"][0].get("data_points") or [])
    return points_from_rrd(column, start, end)


def fetch_history_rest(settings: Settings, targets: List[Target], start: int, end: int) -> Fetched:
    creds = read_secret_file(settings.get("rest_creds_file"), "REST credentials file")
    parts = creds.split(None, 1)
    if len(parts) != 2:
        raise ConfigError("The REST credentials file must hold the automation user name and its secret on one line, separated by a space.")
    user, secret = parts[0], parts[1].strip()
    url = rest_metric_url(settings.get("rest_url"))
    timeout = max(float(settings.get("timeout")), HISTORY_MIN_TIMEOUT)
    context = None
    if url.startswith("https://"):
        if settings.get("rest_verify_tls").lower() in ("no", "false", "0"):
            context = ssl._create_unverified_context()
        else:
            context = ssl.create_default_context(cafile=settings.get("rest_ca_file") or None)
    opener = _opener(context)
    headers = {
        "Authorization": "Bearer %s %s" % (user, secret),
        "Accept": "application/json",
        "Content-Type": "application/json",
        "User-Agent": "occupi-checkmk-push/" + VERSION,
    }

    def one(job: Tuple[Target, int, int]) -> Tuple[Tuple[str, str], Points]:
        target, chunk_start, chunk_end = job
        data = json.dumps(rest_metric_body(settings.get("service"), target, chunk_start, chunk_end)).encode("utf-8")
        request = urllib.request.Request(url, data=data, method="POST", headers=headers)
        try:
            with opener.open(request, timeout=timeout) as response:
                body = json.loads(response.read().decode("utf-8"))
        except urllib.error.HTTPError as err:
            if err.code == 400:
                return (target.host, target.metric), []  # no such history for this host and metric
            raise ReadError("The Checkmk REST API refused the request: HTTP %d" % err.code)
        except (urllib.error.URLError, OSError, ValueError) as err:
            raise ReadError("Could not read the Checkmk REST API: %s" % err)
        return (target.host, target.metric), points_from_rest(body, chunk_start, chunk_end)

    usable = [t for t in targets if _REST_METRIC_ID.match(t.metric)]
    jobs = [(t, a, min(a + REST_SPAN_SECONDS, end)) for t in usable for a in range(start, end, REST_SPAN_SECONDS)]
    out: Fetched = {}
    with concurrent.futures.ThreadPoolExecutor(max_workers=REST_WORKERS) as pool:
        for key, points in pool.map(one, jobs):
            if points:
                merge_points(out, key, points)
    return out


def zone_series(targets: List[Target], fetched: Fetched) -> Tuple[Dict[str, Dict[int, Tuple[int, int]]], int]:
    """zone -> {timestamp: (count, step)}. Metrics naming one zone add up; a gap in all of them is left out.

    Also returns how many readings were over the per-zone limit and left out.
    """
    sums: Dict[str, Dict[int, Tuple[float, int]]] = {}
    for target in targets:
        for ts, (value, step) in fetched.get((target.host, target.metric), {}).items():
            if value is None or value < 0:
                continue
            zone = sums.setdefault(target.zone, {})
            zone[ts] = (zone.get(ts, (0.0, step))[0] + value, step)
    out: Dict[str, Dict[int, Tuple[int, int]]] = {}
    too_big = 0
    for zone, series in sums.items():
        for ts, (value, step) in series.items():
            count = js_round(value)
            if count > MAX_DEVICES_PER_AP:
                too_big += 1
                continue
            out.setdefault(zone, {})[ts] = (count, step)
    return out, too_big


def history_rows(series: Dict[str, Dict[int, Tuple[int, int]]]) -> List[Tuple[str, int, int, int]]:
    """(zone, ts, count, step), one per zone and step, in zone then time order."""
    return [(zone, ts, series[zone][ts][0], series[zone][ts][1]) for zone in sorted(series) for ts in sorted(series[zone])]


def count_gaps(rows: List[Tuple[str, int, int, int]]) -> int:
    """Steps missing between a zone's first and last reading."""
    gaps = 0
    previous: Dict[str, Tuple[int, int]] = {}
    for zone, ts, _count, step in rows:
        if zone in previous:
            before_ts, before_step = previous[zone]
            gaps += max(0, (ts - before_ts) // max(before_step, 1) - 1)
        previous[zone] = (ts, step)
    return gaps


def iso_offset(ts: int) -> str:
    return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%S+00:00")


def write_history_file(path: str, rows: List[Tuple[str, int, int, int]], service: str, start: int, end: int, now: float) -> None:
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8", newline="") as handle:
        handle.write("# occupi-checkmk-history %d\n" % HISTORY_FORMAT)
        handle.write("# service: %s\n" % re.sub(r"[\r\n]", " ", service))
        handle.write("# asked for: %s to %s\n" % (iso_offset(start), iso_offset(end)))
        handle.write("# written: %s\n" % iso_offset(int(now)))
        writer = csv.writer(handle, lineterminator="\n")
        writer.writerow(HISTORY_HEADER)
        for zone, ts, count, step in rows:
            writer.writerow([zone, iso_offset(ts), count, step])
    os.replace(tmp, path)


def describe_step(seconds: int) -> str:
    if seconds % 3600 == 0:
        hours = seconds // 3600
        return "%d hour%s" % (hours, "" if hours == 1 else "s")
    if seconds % 60 == 0:
        return "%d minutes" % (seconds // 60)
    return "%d seconds" % seconds


def _rest_ready(settings: Settings) -> bool:
    return bool(settings.get("rest_url") and settings.get("rest_creds_file"))


def fetch_history(settings: Settings, targets: List[Target], start: int, end: int) -> Fetched:
    """Livestatus first. If that cannot be read and the REST API is set up, that."""
    if settings.get("source") == "livestatus":
        try:
            return fetch_history_livestatus(settings, targets, start, end)
        except ReadError as err:
            if not _rest_ready(settings):
                raise
            LOG.warning("Livestatus could not give the history (%s). Trying the REST API.", err)
    elif not _rest_ready(settings):
        raise ConfigError("The REST source needs rest_url and rest_creds_file.")
    return fetch_history_rest(settings, targets, start, end)


def list_service(settings: Settings) -> List[Dict[str, str]]:
    timeout = float(settings.get("timeout"))
    if settings.get("source") == "rest":
        return read_rest(settings, timeout)
    try:
        return read_livestatus(settings, timeout)
    except ReadError as err:
        if not _rest_ready(settings):
            raise
        LOG.warning("Livestatus could not list the service (%s). Trying the REST API.", err)
        return read_rest(settings, timeout)


def run_backfill(settings: Settings, from_text: str, to_text: str, out_path: Optional[str], now: Optional[float] = None, out: Any = None) -> int:
    out = out or sys.stdout
    now = time.time() if now is None else now
    start, end = resolve_range(from_text, to_text, settings.get("timezone"), now)
    if (end - start) / 86400 > LONG_RANGE_DAYS:
        LOG.warning("That is over %d days. The file may be large; Occupi reads up to 25 MB. Ask for shorter periods if it is.", LONG_RANGE_DAYS)
    try:
        targets = history_targets(list_service(settings))
        if not targets:
            LOG.error("Checkmk has no service called %r with performance data%s.", settings.get("service"), " on " + settings.get("host") if settings.get("host") else "")
            return EXIT_READ
        unreadable = sorted({t.metric for t in targets if _LIVESTATUS_UNSAFE.search(t.metric)})
        if unreadable and settings.get("source") == "livestatus":
            LOG.warning(
                "%d metric names have a space, colon or comma, which Livestatus cannot be asked for by name: %s. They are left out unless the REST API is set up.",
                len(unreadable),
                ", ".join(unreadable[:8]) + (", ..." if len(unreadable) > 8 else ""),
            )
        fetched = fetch_history(settings, targets, start, end)
    except ReadError as err:
        LOG.error("%s", err)
        return EXIT_READ
    series, too_big = zone_series(targets, fetched)
    if too_big:
        LOG.warning("%d readings were over %d devices and were left out.", too_big, MAX_DEVICES_PER_AP)
    rows = history_rows(series)
    if not rows:
        LOG.error("Checkmk holds no history for these zones between %s and %s. Nothing was written.", iso_offset(start), iso_offset(end))
        return EXIT_READ
    empty = sorted({t.zone for t in targets} - set(series))
    if empty:
        LOG.warning("%d zones have no history in that period: %s", len(empty), ", ".join(empty[:8]) + (", ..." if len(empty) > 8 else ""))
    path = out_path or "occupi-history-%s-%s.csv" % (re.sub(r"[^0-9A-Za-z-]", "", from_text), re.sub(r"[^0-9A-Za-z-]", "", to_text))
    write_history_file(path, rows, settings.get("service"), start, end, now)
    steps = Counter(row[3] for row in rows)
    size = os.path.getsize(path)
    print("Wrote %s" % path, file=out)
    print("  zones: %d, rows: %d, size: %.1f MB" % (len(series), len(rows), size / 1048576.0), file=out)
    print("  from %s to %s" % (iso_offset(min(r[1] for r in rows)), iso_offset(max(r[1] for r in rows))), file=out)
    print("  step: %s" % ", ".join("%s (%d rows)" % (describe_step(s), n) for s, n in sorted(steps.items())), file=out)
    print("  gaps left out (no value in Checkmk): %d" % count_gaps(rows), file=out)
    if max(steps) > 3600:
        print("  Note: Checkmk keeps older history in %s steps, too coarse for hourly charts. Occupi will say so on import." % describe_step(max(steps)), file=out)
    if size > LARGE_FILE_BYTES:
        print("  This file is over 20 MB. Occupi reads up to 25 MB. Ask for a shorter period if the upload is refused.", file=out)
    return EXIT_OK


def main(argv: Optional[List[str]] = None, environ: Optional[Dict[str, str]] = None) -> int:
    parser = argparse.ArgumentParser(description="Send Checkmk's per-zone Wi-Fi counts to Occupi.")
    parser.add_argument("--config", help="settings file (default ~/etc/occupi-push.ini)")
    parser.add_argument("--dry-run", action="store_true", help="print what would be sent; send nothing and keep nothing")
    parser.add_argument("--once", action="store_true", help="run once and exit (the only mode; lets a cron line say so)")
    parser.add_argument("--verbose", action="store_true", help="also log to the terminal")
    parser.add_argument("--backfill", nargs=2, metavar=("FROM", "TO"), help="write the service's history between two dates (YYYY-MM-DD, campus time, both days included; or an ISO time) to a CSV file for the Wi-Fi page; sends nothing")
    parser.add_argument("--out", metavar="FILE", help="where --backfill writes its file (default: occupi-history-FROM-TO.csv in this folder)")
    parser.add_argument("--version", action="version", version="occupi-checkmk-push " + VERSION)
    args = parser.parse_args(argv)
    env = dict(os.environ if environ is None else environ)
    try:
        if args.backfill:
            settings = load_settings(args.config, env, require_occupi=False)
            setup_logging(settings.get("log_file"), True)
            return run_backfill(settings, args.backfill[0], args.backfill[1], args.out)
        settings = load_settings(args.config, env)
        setup_logging(settings.get("log_file"), args.verbose or args.dry_run)
        os.makedirs(settings.get("state_dir"), mode=0o700, exist_ok=True)
        with open(os.path.join(settings.get("state_dir"), "lock"), "w") as lock:
            try:
                fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except OSError:
                LOG.warning("Another run is still going; skipping this one.")
                return EXIT_OK
            return run(settings, args.dry_run)
    except ConfigError as err:
        print("occupi-checkmk-push: %s" % err, file=sys.stderr)
        return EXIT_CONFIG


if __name__ == "__main__":
    sys.exit(main())
