#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
agent_yeastar - Checkmk special agent for Yeastar P-Series PBXs, using the OpenAPI
(P550/P560/P570 and P-Series Software Edition).

Installed by the "yeastar" extension package and configured through the rule
"Yeastar P-Series PBX" (Setup > Agents > Other integrations). It can also be run
by hand for testing. Output: a <<<local>>> section (local checks).

Sections (select with --only / --skip):

  system      Yeastar System            model, firmware (+ change detection), uptime, clock drift
  capacity    Yeastar Calls             live concurrent calls / licensed maximum
              Yeastar Extension Licences extensions created / licensed maximum
  storage     Yeastar Storage <name>    free space and connection state of each storage device
  backup      Yeastar Backup            age and result of the latest backup
  certs       Yeastar Certificates      days until the next certificate expires
  trunks      Yeastar Trunk <name>      status of each trunk
  extensions  Yeastar Extensions        registered extensions, split by endpoint type
  queues      Yeastar Queue <name>      waiting/active calls and available agents per queue (live)
  queuestats  Yeastar Queue Statistics <name>  calls, answered/missed/abandoned, SLA, wait times
                                        of the current day and of yesterday (call report)
  archive     Yeastar Archiving         result of the latest archive job of each task
  cdr         Yeastar Calls Today       call volume of the current day (from the CDR) + calls per hour
              Yeastar Calls Yesterday   call volume of the last complete day
  peak        Yeastar Peak Calls        peak concurrent calls today / yesterday (call report)
  recordings  Yeastar Recordings        number of stored recordings

  Yeastar API is always present: reachability, authentication, and the list of
  sections that failed (their services simply go stale in Checkmk).

Python 3 standard library only, no dependencies.

The access token is cached on disk: the PBX only accepts 8 valid tokens at the
same time (30 min lifetime each), so we must NOT request a new one on every run.
"""

import argparse
import datetime
import hashlib
import json
import os
import re
import ssl
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request

USER_AGENT = "OpenAPI"          # mandatory header, the PBX does not answer without it
TOKEN_MARGIN = 120              # renew the token 2 min before it expires

OK, WARN, CRIT, UNKNOWN = 0, 1, 2, 3

SECTIONS = ["system", "capacity", "storage", "backup", "certs", "trunks", "extensions",
            "queues", "queuestats", "archive", "cdr", "peak", "recordings"]

# "status" codes returned by trunk/list (Yeastar P-Series documentation).
# To change the severity of a state, simply edit this table.
TRUNK_STATUS = {
    0:  (WARN, "unknown status"),
    1:  (OK,   "idle"),
    2:  (OK,   "busy (calls in progress)"),
    3:  (OK,   "idle, unmonitored (qualify disabled)"),
    4:  (WARN, "SIP trunk registering"),
    5:  (WARN, "GSM trunk registering"),
    11: (CRIT, "FXO port failure"),
    12: (CRIT, "no PSTN line plugged into the FXO port"),
    21: (CRIT, "E1/BRI unavailable (protocol layer configuration)"),
    22: (CRIT, "E1/BRI failure (interface or module)"),
    23: (CRIT, "E1/BRI unavailable (no line plugged in)"),
    31: (CRIT, "GSM module failure"),
    32: (CRIT, "GSM module powered off"),
    33: (CRIT, "no SIM card"),
    34: (CRIT, "GSM no signal"),
    35: (CRIT, "PIN error"),
    36: (CRIT, "cellular network registration failure"),
    41: (CRIT, "SIP registration failed"),
    42: (CRIT, "SIP trunk unreachable"),
    43: (CRIT, "SIP account trunk unavailable"),
    44: (OK,   "disabled"),
}


class ApiError(Exception):
    pass


# --------------------------------------------------------------------------
# HTTP
# --------------------------------------------------------------------------
class Client:
    def __init__(self, base_url, timeout, insecure, debug=False):
        self.base = base_url.rstrip("/")
        self.timeout = timeout
        self.debug = debug
        self.ctx = None
        if base_url.startswith("https"):
            self.ctx = ssl.create_default_context()
            if insecure:
                self.ctx.check_hostname = False
                self.ctx.verify_mode = ssl.CERT_NONE

    def request(self, endpoint, params=None, body=None, version="v1.0"):
        """GET when body is None, POST (JSON) otherwise. Returns the decoded JSON."""
        url = "%s/openapi/%s/%s" % (self.base, version, endpoint)
        if params:
            url += "?" + urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
        data = None
        headers = {"User-Agent": USER_AGENT}
        if body is not None:
            data = json.dumps(body).encode("utf-8")
            headers["Content-Type"] = "application/json"
        req = urllib.request.Request(url, data=data, headers=headers)
        try:
            with urllib.request.urlopen(req, timeout=self.timeout, context=self.ctx) as resp:
                raw = resp.read().decode("utf-8", "replace")
        except urllib.error.HTTPError as exc:
            raise ApiError("HTTP %s on %s" % (exc.code, endpoint))
        except (urllib.error.URLError, OSError) as exc:
            reason = getattr(exc, "reason", exc)
            raise ApiError("connection failed (%s)" % reason)
        if self.debug and "token" not in endpoint:
            # --debug: raw answers on stderr (tokens are never printed)
            shown = re.sub(r"access_token=[^&]+", "access_token=***", url)
            sys.stderr.write("--- %s\n%s\n" % (shown, raw[:4000]))
        try:
            return json.loads(raw)
        except ValueError:
            raise ApiError("non-JSON response on %s" % endpoint)


# --------------------------------------------------------------------------
# Disk cache: token + small state (firmware seen, yesterday's statistics)
# --------------------------------------------------------------------------
def cache_dir():
    # Inside a Checkmk site: ~/tmp/yeastar/ ; otherwise a per-user temp directory.
    root = os.environ.get("OMD_ROOT")
    directory = os.path.join(root, "tmp", "yeastar") if root else \
        os.path.join(tempfile.gettempdir(), "yeastar-%d" % os.getuid())
    os.makedirs(directory, mode=0o700, exist_ok=True)
    return directory


def cache_file(kind, base_url, client_id):
    # One file per PBX + Client ID.
    key = hashlib.sha256(("%s|%s" % (base_url, client_id)).encode()).hexdigest()[:24]
    return os.path.join(cache_dir(), "%s-%s.json" % (kind, key))


def load_json(path):
    try:
        with open(path) as handle:
            return json.load(handle)
    except (OSError, ValueError):
        return {}


def save_json(path, content):
    # Atomic write, file readable by the owner only.
    tmp = "%s.%d" % (path, os.getpid())
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as handle:
        json.dump(content, handle)
    os.replace(tmp, path)


def check_answer(answer, what):
    """Every API response carries errcode; 0 means success."""
    if not isinstance(answer, dict) or answer.get("errcode") != 0:
        code = answer.get("errcode") if isinstance(answer, dict) else "?"
        msg = answer.get("errmsg", "") if isinstance(answer, dict) else ""
        raise ApiError("%s rejected: errcode=%s %s" % (what, code, msg))
    return answer


def store_token(path, answer):
    now = time.time()
    cache = {
        "access_token": answer["access_token"],
        "access_until": now + int(answer.get("access_token_expire_time", 1800)),
        "refresh_token": answer.get("refresh_token"),
        "refresh_until": now + int(answer.get("refresh_token_expire_time", 0)),
    }
    save_json(path, cache)
    return cache["access_token"]


def get_token(client, path, client_id, secret, force_new=False):
    now = time.time()
    cache = {} if force_new else load_json(path)

    # 1) cached access token still valid
    if cache.get("access_token") and cache.get("access_until", 0) - TOKEN_MARGIN > now:
        return cache["access_token"]

    # 2) access token expired but refresh token still valid (the normal case when
    #    polling every 15 min or more: the refresh token lasts 24 h)
    if cache.get("refresh_token") and cache.get("refresh_until", 0) - TOKEN_MARGIN > now:
        try:
            answer = check_answer(
                client.request("refresh_token", body={"refresh_token": cache["refresh_token"]}),
                "refresh_token")
            return store_token(path, answer)
        except (ApiError, KeyError):
            pass  # fall back to a full authentication

    # 3) full authentication with Client ID / Client Secret
    answer = check_answer(
        client.request("get_token", body={"username": client_id, "password": secret}),
        "get_token")
    if "access_token" not in answer:
        raise ApiError("get_token: no token in the response")
    return store_token(path, answer)


# --------------------------------------------------------------------------
# Helpers
# --------------------------------------------------------------------------
def clean(text):
    """Strip characters that would break the local check line format."""
    return re.sub(r'["\r\n|]+', " ", str(text)).strip()


def service_name(name):
    """Checkmk rejects service names containing ' or " (local check format): queue and
    trunk names such as "File d'attente" get typographic quotes instead."""
    name = clean(name).replace("'", "\u2019").replace('"', "\u201d")
    return re.sub(r"\s+", " ", name).strip() or "unnamed"


def local_line(state, service, text, metrics=None):
    # Local check format: <state> "<service name>" <metrics or -> <text>
    perf = "|".join(metrics) if metrics else "-"
    return '%d "%s" %s %s' % (state, service_name(service), perf, clean(text))


def metric(name, value, warn=None, crit=None, minimum=None, maximum=None):
    """One Checkmk metric: name=value;warn;crit;min;max (plain decimals, no exponent)."""
    def fmt(x):
        if x is None:
            return ""
        return "%d" % x if float(x) == int(x) else ("%.2f" % x)
    fields = [fmt(value), fmt(warn), fmt(crit), fmt(minimum), fmt(maximum)]
    # All metrics share the yeastar_ prefix: the package ships graph definitions for them
    return "yeastar_%s=%s" % (name, ";".join(fields).rstrip(";"))


def fmt_duration(seconds):
    days, rest = divmod(int(seconds), 86400)
    hours, rest = divmod(rest, 3600)
    return "%dd %02dh%02dm" % (days, hours, rest // 60)


def to_int(value, default=0):
    try:
        return int(float(value))
    except (TypeError, ValueError):
        return default


def parse_size(text):
    """'6.14G' / '512M' / '1.2T' -> bytes (None if not understood)."""
    match = re.match(r"^\s*([\d.]+)\s*([KMGTP]?)i?B?\s*$", str(text), re.I)
    if not match:
        return None
    power = "KMGTP".find(match.group(2).upper()) + 1 if match.group(2) else 0
    return float(match.group(1)) * (1024 ** power)


def level_above(value, warn, crit):
    """State for 'higher is worse' thresholds (None = no threshold)."""
    if crit is not None and value >= crit:
        return CRIT
    if warn is not None and value >= warn:
        return WARN
    return OK


def level_below(value, warn, crit):
    """State for 'lower is worse' thresholds (None = no threshold)."""
    if crit is not None and value < crit:
        return CRIT
    if warn is not None and value < warn:
        return WARN
    return OK


class Ctx:
    """Everything a section needs: API access, options, PBX clock, persistent state."""

    def __init__(self, client, token, args, state):
        self.client, self.token, self.args, self.state = client, token, args, state
        self.info = {}
        self.date_fmt = "%Y/%m/%d"
        self.twelve_hour = False
        self.now = datetime.datetime.now()   # PBX local time, refined by set_info()
        self.trunks = None
        self.queues = None

    def api(self, endpoint, params=None, version="v1.0"):
        query = dict(params or {})
        query["access_token"] = self.token
        return check_answer(self.client.request(endpoint, params=query, version=version), endpoint)

    def api_list(self, endpoint, key="data", params=None, page_size=100, max_pages=50):
        """Read a paginated list endpoint completely."""
        items, page = [], 1
        while page <= max_pages:
            query = dict(params or {})
            query.update({"page": page, "page_size": page_size})
            answer = self.api(endpoint, query)
            chunk = answer.get(key) or []
            items.extend(chunk)
            total = to_int(answer.get("total_number"), len(items))
            if not chunk or len(items) >= total:
                break
            page += 1
        return items

    def set_info(self, data):
        """Learn the PBX date/time display format: API date filters must use it."""
        self.info = data
        fmt = str(data.get("system_date_format") or "YYYY/MM/DD")
        self.date_fmt = fmt.replace("YYYY", "%Y").replace("MM", "%m").replace("DD", "%d")
        system_time = str(data.get("system_time") or "")
        self.twelve_hour = bool(re.search(r"[AP]M", system_time, re.I))
        parsed = self.parse_dt(system_time)
        if parsed:
            self.now = parsed

    def fmt_dt(self, moment):
        return moment.strftime(self.date_fmt + (" %I:%M:%S %p" if self.twelve_hour else " %H:%M:%S"))

    def parse_dt(self, text):
        text = str(text or "").strip()
        dates = [self.date_fmt, "%Y/%m/%d", "%d/%m/%Y", "%m/%d/%Y", "%Y-%m-%d"]
        for date in dates:
            for clock in (" %H:%M:%S", " %I:%M:%S %p", ""):
                try:
                    return datetime.datetime.strptime(text, date + clock)
                except ValueError:
                    continue
        return None

    def get_trunks(self):
        if self.trunks is None:
            self.trunks = self.api_list("trunk/list")
        return self.trunks

    def get_queues(self):
        if self.queues is None:
            self.queues = self.api_list("queue/list", key="queue_list")
        return self.queues


# --------------------------------------------------------------------------
# Sections
# --------------------------------------------------------------------------
def sec_system(ctx):
    args, data = ctx.args, ctx.info
    uptime = to_int(data.get("up_time"))
    firmware = str(data.get("firmware_version", "?"))
    state = OK
    notes = []

    if args.uptime_warn and uptime < args.uptime_warn:
        state = max(state, WARN)
        notes.append("recent reboot")

    # Clock drift between the PBX and this server
    drift = None
    if data.get("timestamp"):
        drift = abs(time.time() - to_int(data["timestamp"]))
        if args.clock_warn and drift > args.clock_warn:
            state = max(state, WARN)
            notes.append("clock drift %ds" % drift)

    # Firmware change detection: WARN for 24 h after the version changes
    seen = ctx.state.get("firmware")
    if seen and seen.get("version") != firmware:
        ctx.state["firmware"] = {"version": firmware, "previous": seen.get("version"),
                                 "changed_at": time.time()}
    elif not seen:
        ctx.state["firmware"] = {"version": firmware}
    seen = ctx.state["firmware"]
    if seen.get("changed_at") and time.time() - seen["changed_at"] < 86400:
        state = max(state, WARN)
        notes.append("firmware changed from %s" % seen.get("previous"))

    text = "%s, firmware %s, SN %s, uptime %s" % (
        data.get("model_name", "?"), firmware, data.get("sn", "?"), fmt_duration(uptime))
    if notes:
        text += " (%s)" % ", ".join(notes)
    metrics = [metric("uptime", uptime)]
    if drift is not None:
        metrics.append(metric("clock_drift", drift, args.clock_warn or None))
    return [local_line(state, "Yeastar System", text, metrics)]


def sec_capacity(ctx):
    args = ctx.args
    data = ctx.api("system/capacity").get("data") or {}
    lines = []

    # Live concurrent calls (thresholds in percent of the licensed maximum)
    calls, calls_max = to_int(data.get("cc_used")), to_int(data.get("cc_capacity"))
    warn = calls_max * args.calls_warn / 100.0 if calls_max else None
    crit = calls_max * args.calls_crit / 100.0 if calls_max else None
    text = "%d concurrent call(s), maximum %d" % (calls, calls_max)
    if calls_max:
        text += " (%.0f%%)" % (100.0 * calls / calls_max)
    lines.append(local_line(level_above(calls, warn, crit), "Yeastar Calls", text,
                            [metric("concurrent_calls", calls, warn, crit, 0, calls_max or None)]))

    # Extension licences
    used, maximum = to_int(data.get("extension_used")), to_int(data.get("extension_capacity"))
    warn = maximum * args.licence_warn / 100.0 if maximum else None
    crit = maximum * args.licence_crit / 100.0 if maximum else None
    text = "%d of %d extension licences used" % (used, maximum)
    if maximum:
        text += " (%.0f%%)" % (100.0 * used / maximum)
    lines.append(local_line(level_above(used, warn, crit), "Yeastar Extension Licences", text,
                            [metric("licences_used", used, warn, crit, 0, maximum or None)]))
    return lines


def sec_storage(ctx):
    args, lines = ctx.args, []
    for device in ctx.api("storage/list").get("storage_list") or []:
        name = clean(device.get("name", "id%s" % device.get("id")))
        status = str(device.get("status", "?"))
        total, free = parse_size(device.get("total")), parse_size(device.get("available"))
        state, metrics = OK, None
        text = "%s, %s" % (device.get("type", "?"), status)
        if status.lower() in ("not_inserted", "not inserted", "uninserted"):
            # empty USB/SD slot of an appliance: normal unless the device is needed
            lines.append(local_line(OK, "Yeastar Storage %s" % name,
                                    "%s, no device inserted" % device.get("type", "?")))
            continue
        if status.lower() != "connected":
            state = CRIT
        if total and free is not None:
            used_pct = 100.0 * (total - free) / total
            state = max(state, level_above(used_pct, args.storage_warn, args.storage_crit))
            text += ", %.1f%% used, %s free of %s" % (used_pct, device.get("available"), device.get("total"))
            metrics = [metric("storage_used_percent", round(used_pct, 2), args.storage_warn, args.storage_crit, 0, 100),
                       metric("storage_used", int(total - free), None, None, 0, int(total))]
        lines.append(local_line(state, "Yeastar Storage %s" % name, text, metrics))
    return lines


def sec_backup(ctx):
    args = ctx.args
    answer = ctx.api("backup/list", {"page": 1, "page_size": 50,
                                     "sort_by": "backup_time", "order_by": "desc"})
    backups = answer.get("backup_list") or []
    if not backups:
        return [local_line(WARN, "Yeastar Backup", "no backup file on the PBX")]

    # Newest first, whatever order the PBX returned
    dated = [(ctx.parse_dt(b.get("backup_time")), b) for b in backups]
    dated = [(moment, b) for moment, b in dated if moment]
    if not dated:
        return [local_line(UNKNOWN, "Yeastar Backup",
                           "cannot read backup dates (e.g. %r)" % backups[0].get("backup_time"))]
    dated.sort(key=lambda pair: pair[0], reverse=True)
    latest_time, latest = dated[0]
    good = [moment for moment, b in dated if str(b.get("backup_status", "")).lower() == "success"]

    state, notes = OK, []
    if str(latest.get("backup_status", "")).lower() == "failed":
        state = WARN
        notes.append("latest backup FAILED (%s)" % latest.get("file_name"))
    if not good:
        return [local_line(CRIT, "Yeastar Backup",
                           "no successful backup among %d file(s)" % len(backups))]
    age_days = max(0.0, (ctx.now - good[0]).total_seconds() / 86400.0)
    state = max(state, level_above(age_days, args.backup_warn, args.backup_crit))
    text = "last successful backup %.1f day(s) ago (%s), %d file(s)" % (
        age_days, good[0].strftime("%Y-%m-%d %H:%M"), to_int(answer.get("total_number"), len(backups)))
    if notes:
        text += ", " + ", ".join(notes)
    return [local_line(state, "Yeastar Backup", text,
                       [metric("backup_age_days", round(age_days, 2), args.backup_warn, args.backup_crit, 0)])]


def sec_certs(ctx):
    args = ctx.args
    certs = ctx.api("certificate/list").get("certificate_list") or []
    if not certs:
        return [local_line(OK, "Yeastar Certificates", "no certificate imported on the PBX")]
    soonest, unreadable = [], 0
    for cert in certs:
        expires = ctx.parse_dt(cert.get("expiration"))
        if not expires:
            unreadable += 1
            continue
        days = (expires - ctx.now).total_seconds() / 86400.0
        soonest.append((days, cert))
    if not soonest:
        return [local_line(UNKNOWN, "Yeastar Certificates",
                           "cannot read expiration dates (e.g. %r)" % certs[0].get("expiration"))]
    soonest.sort(key=lambda pair: pair[0])
    days, cert = soonest[0]
    # 'lower is worse': thresholds are days left
    state = level_below(days, args.cert_warn, args.cert_crit)
    label = "expired %.0f day(s) ago" % -days if days < 0 else "expires in %.0f day(s)" % days
    text = "%d certificate(s), next: %s (%s, %s) %s" % (
        len(certs), cert.get("name", "?"), cert.get("type", "?"), cert.get("issue_to", "?"), label)
    if unreadable:
        text += ", %d with unreadable date" % unreadable
    return [local_line(state, "Yeastar Certificates", text,
                       [metric("cert_days_left", round(days, 1), args.cert_warn, args.cert_crit)])]


def sec_trunks(ctx):
    lines = []
    ignore = re.compile(ctx.args.ignore_trunk) if ctx.args.ignore_trunk else None
    for trunk in ctx.get_trunks():
        name = clean(trunk.get("name", "id%s" % trunk.get("id")))
        if ignore and ignore.search(name):
            continue
        code = trunk.get("status")
        state, label = TRUNK_STATUS.get(code, (UNKNOWN, "undocumented status code"))
        text = "%s (code %s), type %s" % (label, code, trunk.get("type", "?"))
        if trunk.get("host_port"):
            text += ", %s" % trunk["host_port"]
        metrics = None
        if "gsm_signal_level" in trunk:
            metrics = [metric("gsm_signal", to_int(trunk["gsm_signal_level"]))]
        lines.append(local_line(state, "Yeastar Trunk %s" % name, text, metrics))
    return lines


def sec_extensions(ctx):
    args = ctx.args
    extensions = ctx.api_list("extension/list")
    total, registered, by_type = len(extensions), 0, {}
    for ext in extensions:
        online = False
        for kind, endpoint in (ext.get("online_status") or {}).items():
            if not isinstance(endpoint, dict):
                continue
            # SIP endpoints report their state in status_list, the others in status
            up = endpoint.get("status") == 1 or any(
                isinstance(e, dict) and e.get("status") == 1 for e in endpoint.get("status_list") or [])
            by_type.setdefault(kind, 0)
            if up:
                by_type[kind] += 1
                online = True
        registered += 1 if online else 0
    state = level_below(registered, args.ext_warn, args.ext_crit)
    text = "%d of %d extension(s) registered" % (registered, total)
    if by_type:
        text += " (" + ", ".join("%s %d" % (k, v) for k, v in sorted(by_type.items())) + ")"
    metrics = [metric("ext_registered", registered, args.ext_warn, args.ext_crit, 0, total),
               metric("ext_total", total)]
    metrics += [metric("ep_" + re.sub(r"\W", "_", kind), count) for kind, count in sorted(by_type.items())]
    return [local_line(state, "Yeastar Extensions", text, metrics)]


def sec_queues(ctx):
    args, lines = ctx.args, []
    for queue in ctx.get_queues():
        qid = queue.get("id")
        name = clean(queue.get("name") or queue.get("number") or "id%s" % qid)
        calls = ctx.api("queue/call_status", {"id": qid})
        waiting = to_int(calls.get("waiting_calls"))
        active = to_int(calls.get("active_calls"))
        ringing = to_int(calls.get("ringing_calls"))
        longest = max([to_int(c.get("duration")) for c in calls.get("waiting_list") or []] or [0])

        agents = ctx.api("queue/agent_status", {"id": qid}).get("data") or []
        logged_in = [a for a in agents if a.get("is_login") == 1]
        available = [a for a in logged_in if a.get("is_pause") != 1]

        state = level_above(waiting, args.queue_wait_warn, args.queue_wait_crit)
        text = "%d waiting (longest %ds), %d active, %d ringing, agents %d available / %d logged in / %d total" % (
            waiting, longest, active, ringing, len(available), len(logged_in), len(agents))
        if args.queue_min_agents is not None and len(available) < args.queue_min_agents:
            state = max(state, WARN)
            text += " (fewer than %d agent(s) available)" % args.queue_min_agents
        lines.append(local_line(state, "Yeastar Queue %s" % name, text, [
            metric("queue_waiting", waiting, args.queue_wait_warn, args.queue_wait_crit, 0),
            metric("queue_longest_wait", longest), metric("queue_active", active),
            metric("agents_available", len(available)), metric("agents_logged_in", len(logged_in))]))
    return lines


QUEUE_FIELDS = ["total_calls", "answered_calls", "missed_calls", "abandoned_calls", "sla",
                "average_waiting_time", "max_waiting_time", "average_talking_time"]


def queue_perf_day(ctx, day, queue_ids):
    """'Queue Performance' report of one PBX-local day, keyed by queue number and name."""
    params = {"type": "queueperformance", "queue_id_list": queue_ids,
              "start_time": ctx.fmt_dt(datetime.datetime.combine(day, datetime.time(0, 0, 0))),
              "end_time": ctx.fmt_dt(datetime.datetime.combine(day, datetime.time(23, 59, 59)))}
    error = None
    # New report data lives under openapi/v2.0, legacy data under v1.0
    for version in ("v2.0", "v1.0"):
        try:
            rows = ctx.api("call_report/list", params, version=version).get("queue_performance_list") or []
        except ApiError as exc:
            error = exc
            continue
        result = {}
        for row in rows:
            stats = dict((field, float(row.get(field) or 0)) for field in QUEUE_FIELDS)
            for key in (row.get("queue_num"), row.get("queue")):
                if key not in (None, ""):
                    result[str(key)] = stats
        return result
    raise error


def sec_queuestats(ctx):
    args, queues = ctx.args, ctx.get_queues()
    if not queues:
        return []
    ids = ",".join(str(q.get("id")) for q in queues if q.get("id") is not None)
    today = ctx.now.date()
    yesterday = today - datetime.timedelta(days=1)
    now = queue_perf_day(ctx, today, ids)
    # Yesterday never changes: compute it once and keep it in the state file
    cached = ctx.state.get("queue_yesterday") or {}
    if cached.get("day") != yesterday.isoformat() or cached.get("ids") != ids:
        cached = {"day": yesterday.isoformat(), "ids": ids, "stats": queue_perf_day(ctx, yesterday, ids)}
        ctx.state["queue_yesterday"] = cached
    empty = dict((field, 0.0) for field in QUEUE_FIELDS)
    lines = []
    for queue in queues:
        name = clean(queue.get("name") or queue.get("number") or "id%s" % queue.get("id"))
        keys = [str(queue.get("number")), str(queue.get("name"))]
        t = next((now[k] for k in keys if k in now), empty)
        y = next((cached["stats"][k] for k in keys if k in cached["stats"]), empty)
        state = OK
        # SLA thresholds only make sense once the queue has received a few calls
        if t["total_calls"] >= args.queue_sla_min_calls:
            state = level_below(t["sla"], args.queue_sla_warn, args.queue_sla_crit)
        text = ("today: %d call(s), %d answered, %d missed, %d abandoned, SLA %.0f%%, "
                "wait avg %ds / max %ds, talk avg %ds - yesterday: %d call(s), %d answered, "
                "%d missed, %d abandoned, SLA %.0f%%") % (
                    t["total_calls"], t["answered_calls"], t["missed_calls"], t["abandoned_calls"], t["sla"],
                    t["average_waiting_time"], t["max_waiting_time"], t["average_talking_time"],
                    y["total_calls"], y["answered_calls"], y["missed_calls"], y["abandoned_calls"], y["sla"])
        lines.append(local_line(state, "Yeastar Queue Statistics %s" % name, text, [
            metric("q_calls", t["total_calls"]), metric("q_answered", t["answered_calls"]),
            metric("q_missed", t["missed_calls"]), metric("q_abandoned", t["abandoned_calls"]),
            metric("q_sla", t["sla"], args.queue_sla_warn, args.queue_sla_crit, 0, 100),
            metric("q_avg_wait", t["average_waiting_time"]), metric("q_max_wait", t["max_waiting_time"]),
            metric("q_avg_talk", t["average_talking_time"]),
            metric("q_calls_yesterday", y["total_calls"]), metric("q_answered_yesterday", y["answered_calls"]),
            metric("q_missed_yesterday", y["missed_calls"]), metric("q_abandoned_yesterday", y["abandoned_calls"]),
            metric("q_sla_yesterday", y["sla"], None, None, 0, 100)]))
    return lines


def sec_archive(ctx):
    logs = ctx.api("archival_logs/list", {"page": 1, "page_size": 50,
                                          "sort_by": "id", "order_by": "desc"}).get("data") or []
    if not logs:
        return [local_line(OK, "Yeastar Archiving", "no archival log (archiving not used)")]
    # Keep the most recent log of each archive task
    latest = {}
    for log in sorted(logs, key=lambda l: to_int(l.get("id")), reverse=True):
        latest.setdefault(str(log.get("name")), log)
    bad = [l for l in latest.values() if str(l.get("execution_result", "")).lower() != "success"]
    state = WARN if bad else OK
    text = "%d archive task(s), all last runs successful" % len(latest)
    if bad:
        text = "%d of %d archive task(s) not successful: %s" % (
            len(bad), len(latest),
            ", ".join("%s=%s (%s)" % (l.get("name"), l.get("execution_result"), l.get("execution_time"))
                      for l in bad))
    return [local_line(state, "Yeastar Archiving", text, [metric("archive_tasks_failed", len(bad))])]


def cdr_day(ctx, day):
    """Tally the CDRs of one PBX-local day. Date filters must use the PBX display format."""
    start = datetime.datetime.combine(day, datetime.time(0, 0, 0))
    end = datetime.datetime.combine(day, datetime.time(23, 59, 59))
    stats = {"total": 0, "inbound": 0, "outbound": 0, "internal": 0,
             "answered": 0, "unanswered": 0, "talk": 0, "partial": False}
    page, seen = 1, 0
    while page <= 5:                       # hard cap: 5 x 10,000 records per run
        answer = ctx.api("cdr/search", {"start_time": ctx.fmt_dt(start), "end_time": ctx.fmt_dt(end),
                                        "page": page, "page_size": 10000})
        records = answer.get("data") or []
        stats["total"] = to_int(answer.get("total_number"), seen + len(records))
        for rec in records:
            kind = str(rec.get("call_type", "")).lower()
            if kind in ("inbound", "outbound", "internal"):
                stats[kind] += 1
            status = str(rec.get("disposition") or rec.get("last_status") or "").upper()
            stats["answered" if status == "ANSWERED" else "unanswered"] += 1
            stats["talk"] += to_int(rec.get("talk_duration"))
        seen += len(records)
        if not records or seen >= stats["total"]:
            break
        page += 1
    stats["partial"] = seen < stats["total"]
    return stats


def cdr_line(service, day, stats, extra=None):
    text = "%s: %d call(s) - %d inbound, %d outbound, %d internal - %d answered, %d not answered, talk time %s" % (
        day.isoformat(), stats["total"], stats["inbound"], stats["outbound"], stats["internal"],
        stats["answered"], stats["unanswered"], fmt_duration(stats["talk"]))
    if stats.get("partial"):
        text += " (breakdown computed on the first 50,000 records only)"
    return local_line(OK, service, text, [
        metric("calls_total", stats["total"]), metric("calls_inbound", stats["inbound"]),
        metric("calls_outbound", stats["outbound"]), metric("calls_internal", stats["internal"]),
        metric("calls_answered", stats["answered"]), metric("calls_unanswered", stats["unanswered"]),
        metric("talk_time", stats["talk"])] + (extra or []))


def sec_cdr(ctx):
    today = ctx.now.date()
    yesterday = today - datetime.timedelta(days=1)
    stats = cdr_day(ctx, today)

    # Calls per hour since the previous run (smooth activity curve, unlike the daily counter)
    last, stamp, rate = ctx.state.get("cdr_last") or {}, time.time(), 0.0
    if last.get("day") == today.isoformat() and stamp - last.get("ts", stamp) >= 60:
        rate = max(0, stats["total"] - last.get("total", 0)) * 3600.0 / (stamp - last["ts"])
    elif last and last.get("day") != today.isoformat():
        since_midnight = ctx.now.hour * 3600 + ctx.now.minute * 60 + ctx.now.second
        rate = stats["total"] * 3600.0 / max(since_midnight, 60)
    ctx.state["cdr_last"] = {"day": today.isoformat(), "total": stats["total"], "ts": stamp}

    lines = [cdr_line("Yeastar Calls Today", today, stats, [metric("calls_per_hour", round(rate, 2))])]
    # Yesterday never changes: compute it once and keep it in the state file
    cached = ctx.state.get("cdr_yesterday") or {}
    if cached.get("day") != yesterday.isoformat():
        cached = {"day": yesterday.isoformat(), "stats": cdr_day(ctx, yesterday)}
        ctx.state["cdr_yesterday"] = cached
    lines.append(cdr_line("Yeastar Calls Yesterday", yesterday, cached["stats"]))
    return lines


def peak_day(ctx, day, trunk_ids):
    """Peak concurrent calls of one day from the 'PBX Call Activity' report (hourly rows)."""
    params = {"type": "trunkactivity", "time": day.strftime(ctx.date_fmt),
              "trunk_id_list": trunk_ids, "include_internal": 1}
    error = None
    # New report data lives under openapi/v2.0, legacy data under v1.0
    for version in ("v2.0", "v1.0"):
        try:
            rows = ctx.api("call_report/list", params, version=version).get("trunk_activity_list") or []
        except ApiError as exc:
            error = exc
            continue
        peak, calls = 0, 0
        for row in rows:
            entries = row.get("trunk_list") or []
            # The 'Device' entry is the system-wide total of the hour
            device = [e for e in entries if str(e.get("trunk_name")) == "Device"] or entries
            peak = max([peak] + [to_int(e.get("max_concurrent_call")) for e in device])
            calls += sum(to_int(e.get("total_calls")) for e in device[:1])
        return {"peak": peak, "calls": calls}
    raise error


def sec_peak(ctx):
    trunk_ids = ",".join(str(t.get("id")) for t in ctx.get_trunks() if t.get("id") is not None)
    if not trunk_ids:
        return [local_line(OK, "Yeastar Peak Calls", "no trunk configured, no activity report")]
    today = ctx.now.date()
    yesterday = today - datetime.timedelta(days=1)
    now = peak_day(ctx, today, trunk_ids)
    cached = ctx.state.get("peak_yesterday") or {}
    if cached.get("day") != yesterday.isoformat():
        cached = {"day": yesterday.isoformat(), "stats": peak_day(ctx, yesterday, trunk_ids)}
        ctx.state["peak_yesterday"] = cached
    return [local_line(OK, "Yeastar Peak Calls",
                       "peak concurrent calls: %d today so far, %d yesterday" % (
                           now["peak"], cached["stats"]["peak"]),
                       [metric("peak_today", now["peak"], None, None, 0),
                        metric("peak_yesterday", cached["stats"]["peak"], None, None, 0)])]


def sec_recordings(ctx):
    answer = ctx.api("recording/list", {"page": 1, "page_size": 1})
    total = to_int(answer.get("total_number"))
    return [local_line(OK, "Yeastar Recordings", "%d recording(s) stored" % total,
                       [metric("recordings", total)])]


SECTION_FUNCS = {
    "system": sec_system, "capacity": sec_capacity, "storage": sec_storage, "backup": sec_backup,
    "certs": sec_certs, "trunks": sec_trunks, "extensions": sec_extensions, "queues": sec_queues,
    "queuestats": sec_queuestats, "archive": sec_archive, "cdr": sec_cdr, "peak": sec_peak, "recordings": sec_recordings,
}


# --------------------------------------------------------------------------
# Main
# --------------------------------------------------------------------------
def collect(args, secret):
    base_url = "%s://%s:%d" % (args.scheme, args.host, args.port)
    client = Client(base_url, args.timeout, args.insecure, args.debug)
    token_path = cache_file("token", base_url, args.client_id)
    state_path = cache_file("state", base_url, args.client_id)

    token = get_token(client, token_path, args.client_id, secret)
    ctx = Ctx(client, token, args, load_json(state_path))
    try:
        info = ctx.api("system/information")
    except ApiError:
        # Token revoked on the PBX side (reboot, secret changed...): retry once with a new one
        ctx.token = get_token(client, token_path, args.client_id, secret, force_new=True)
        info = ctx.api("system/information")
    ctx.set_info(info.get("data") or {})

    enabled = [s for s in SECTIONS if (not args.only or s in args.only) and s not in args.skip]
    lines, failed = [], []
    for name in enabled:
        try:
            lines.extend(SECTION_FUNCS[name](ctx))
        except ApiError as exc:
            failed.append("%s (%s)" % (name, exc))
        except Exception as exc:            # a parsing surprise must not kill the other sections
            failed.append("%s (script error: %r)" % (name, exc))

    save_json(state_path, ctx.state)

    if failed:
        api = local_line(WARN, "Yeastar API", "API reachable, but %d section(s) failed: %s" % (
            len(failed), "; ".join(failed)))
    else:
        api = local_line(OK, "Yeastar API", "API reachable, authentication OK, %d section(s) read" % len(enabled))
    return [api] + lines


def section_list(text):
    if text.strip() == "none":          # only the Yeastar API service
        return ["none"]
    names = [n.strip() for n in text.split(",") if n.strip()]
    unknown = [n for n in names if n not in SECTIONS]
    if unknown:
        raise argparse.ArgumentTypeError("unknown section(s): %s (valid: %s)" % (
            ", ".join(unknown), ", ".join(SECTIONS)))
    return names


def main():
    p = argparse.ArgumentParser(prog="agent_yeastar", description="Checkmk special agent for Yeastar P-Series PBXs")
    p.add_argument("--host", required=True, help="PBX IP address or hostname")
    p.add_argument("--port", type=int, default=8088, help="HTTPS port of the web portal (default 8088)")
    p.add_argument("--scheme", default="https", choices=["https", "http"])
    p.add_argument("--client-id", required=True, help="Client ID (Integrations > API)")
    p.add_argument("--client-secret", help="Client Secret (visible in 'ps': prefer --secret-file)")
    p.add_argument("--secret-file", help="file containing the Client Secret (chmod 600)")
    p.add_argument("--insecure", action="store_true", help="do not verify the TLS certificate (self-signed)")
    p.add_argument("--timeout", type=int, default=20)
    p.add_argument("--only", type=section_list, default=[], metavar="LIST",
                   help="comma-separated sections to run (default: all): " + ",".join(SECTIONS))
    p.add_argument("--skip", type=section_list, default=[], metavar="LIST",
                   help="comma-separated sections to leave out")
    p.add_argument("--debug", action="store_true", help="print the raw API answers on stderr")

    t = p.add_argument_group("thresholds")
    t.add_argument("--uptime-warn", type=int, default=1800,
                   help="WARN if uptime is below N seconds (default 1800, 0 = off)")
    t.add_argument("--clock-warn", type=int, default=300,
                   help="WARN if the PBX clock differs by more than N seconds (default 300, 0 = off)")
    t.add_argument("--calls-warn", type=float, default=80, help="concurrent calls, %% of maximum (default 80)")
    t.add_argument("--calls-crit", type=float, default=95, help="concurrent calls, %% of maximum (default 95)")
    t.add_argument("--licence-warn", type=float, default=90, help="extension licences used, %% (default 90)")
    t.add_argument("--licence-crit", type=float, default=100, help="extension licences used, %% (default 100)")
    t.add_argument("--storage-warn", type=float, default=80, help="storage used, %% (default 80)")
    t.add_argument("--storage-crit", type=float, default=90, help="storage used, %% (default 90)")
    t.add_argument("--backup-warn", type=float, default=8, help="days since last good backup (default 8)")
    t.add_argument("--backup-crit", type=float, default=31, help="days since last good backup (default 31)")
    t.add_argument("--cert-warn", type=float, default=30, help="days before certificate expiry (default 30)")
    t.add_argument("--cert-crit", type=float, default=7, help="days before certificate expiry (default 7)")
    t.add_argument("--ext-warn", type=int, help="WARN if fewer than N extensions are registered")
    t.add_argument("--ext-crit", type=int, help="CRIT if fewer than N extensions are registered")
    t.add_argument("--queue-wait-warn", type=int, default=5, help="callers waiting in a queue (default 5)")
    t.add_argument("--queue-wait-crit", type=int, default=10, help="callers waiting in a queue (default 10)")
    t.add_argument("--queue-min-agents", type=int, help="WARN if fewer than N agents are available in a queue")
    t.add_argument("--queue-sla-warn", type=float, help="WARN if today's queue SLA is below N %%")
    t.add_argument("--queue-sla-crit", type=float, help="CRIT if today's queue SLA is below N %%")
    t.add_argument("--queue-sla-min-calls", type=int, default=10,
                   help="apply the SLA thresholds only from N calls received today (default 10)")
    t.add_argument("--ignore-trunk", metavar="REGEX", help="trunks to skip (e.g. '^FXO1-[5-8]$')")
    args = p.parse_args()

    # Minimal agent header so Checkmk accepts the output as agent data
    print("<<<check_mk>>>")
    print("Version: yeastar-openapi-3.1")
    print("AgentOS: yeastar-p-series")
    print("<<<local>>>")

    try:
        if args.secret_file:
            with open(os.path.expanduser(args.secret_file)) as handle:
                secret = handle.read().strip()
        elif args.client_secret:
            secret = args.client_secret
        else:
            raise ApiError("neither --client-secret nor --secret-file given")
        lines = collect(args, secret)
    except ApiError as exc:
        lines = [local_line(CRIT, "Yeastar API", "FAILED: %s" % exc)]
    except Exception as exc:  # never crash the agent run: report the error in the service instead
        lines = [local_line(UNKNOWN, "Yeastar API", "script error: %r" % exc)]

    print("\n".join(lines))
    return 0


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