#!/usr/bin/env python3
"""Monitors as code for WatchCore: create monitors from a YAML or JSON file and keep them in sync through the API.

    pip install pyyaml                        # only for .yaml/.yml files; .json works without it
    export WATCHCORE_KEY=myk_live_...         # API key from Settings, Integrations & API (PRO plan)
    python watchcore_monitors.py monitors.yaml                  # dry run: only shows what would change
    python watchcore_monitors.py monitors.yaml --apply          # creates and updates
    python watchcore_monitors.py monitors.yaml --apply --prune  # also deletes missing monitors, see below

File format:

    project: Shop                # project for monitors without their own (default: General)
    monitors:
      - name: Shop               # project and name identify a monitor
        url: https://shop.example.com
        type: http               # default http; the type of an existing monitor cannot change
        interval: 60             # seconds
        keyword: Warenkorb       # keyword and tags are short for settings: {keyword: ..., tags: [...]}
        settings: {login_is_down: true}
        assertions:              # json_query rules
          - {path: $.status, operator: "==", expected: UP}
        paused: false
        is_public: true          # also: sla, notify, maintenance_windows

Only the fields in the file are compared and changed, everything else stays as it is (alert channels too, unless the
file sets notify). --prune deletes monitors that the file does not list, but only in projects that have at least one
monitor in the file. Write values the way the server keeps them: full URLs with https:// and intervals not below the
minimum of your plan; otherwise the script reports a difference on every run (it says so after --apply).
WATCHCORE_URL changes the API address (default https://watchcore.de/api/v1). Needs Python 3.9 or newer.
"""
import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.request
from urllib.parse import quote

API = os.environ.get("WATCHCORE_URL", "https://watchcore.de/api/v1").rstrip("/")
KEY = os.environ.get("WATCHCORE_KEY", "")
FIELDS = ("name", "project", "type", "url", "interval", "paused", "is_public", "assertions", "sla", "notify",
          "maintenance_windows")
SHORT_SETTINGS = ("keyword", "tags")


def call(method, path, body=None, tries=3):
    """One API request; waits and tries again when the rate limit answers 429. Errors as RuntimeError with the reason."""
    request = urllib.request.Request(API + path, method=method, data=None if body is None else json.dumps(body).encode(),
                                     headers={"X-API-KEY": KEY, "Content-Type": "application/json",
                                              "Accept": "application/json", "User-Agent": "watchcore_monitors.py"})
    for attempt in range(tries):
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                raw = response.read()
            return json.loads(raw) if raw else None
        except urllib.error.HTTPError as err:
            if err.code == 429 and attempt < tries - 1:
                wait = err.headers.get("Retry-After") or ""
                time.sleep(int(wait) if wait.isdigit() else 60)
                continue
            try:
                answer = json.loads(err.read() or b"{}")
            except ValueError:
                answer = {}
            detail = answer.get("detail") if isinstance(answer, dict) else None
            raise RuntimeError(f"{method} {path}: HTTP {err.code} {detail or err.reason}") from None
        except urllib.error.URLError as err:
            raise RuntimeError(f"{method} {path}: {err.reason}") from None


def load(path):
    with open(path, encoding="utf-8") as f:
        text = f.read()
    if not path.lower().endswith((".yaml", ".yml")):
        return json.loads(text)
    try:
        import yaml
    except ImportError:
        raise ValueError("reading YAML needs PyYAML: pip install pyyaml (or use a .json file)") from None
    try:
        return yaml.safe_load(text) or {}
    except yaml.YAMLError as err:
        raise ValueError(f"{path}: {err}") from None


def desired(doc):
    """The monitors of the file as {(project, name): fields for the API}. ValueError on mistakes in the file."""
    if not isinstance(doc, dict) or not isinstance(doc.get("monitors", []), list):
        raise ValueError("the file needs a list under monitors (and optionally a project)")
    default_project = str(doc.get("project") or "General").strip()
    result = {}
    for i, entry in enumerate(doc.get("monitors") or [], 1):
        if not isinstance(entry, dict) or not str(entry.get("name") or "").strip():
            raise ValueError(f"monitor {i}: needs a name")
        unknown = set(entry) - set(FIELDS) - set(SHORT_SETTINGS) - {"settings"}
        if unknown:
            raise ValueError(f"monitor {i} ({entry['name']}): unknown field(s) {', '.join(sorted(unknown))}")
        if not isinstance(entry.get("settings") or {}, dict):
            raise ValueError(f"monitor {i} ({entry['name']}): settings must be a mapping")
        fields = {k: entry[k] for k in FIELDS if k in entry}
        fields.update(name=str(entry["name"]).strip(), project=str(entry.get("project") or default_project).strip(),
                      type=str(entry.get("type") or "http").lower())
        settings = dict(entry.get("settings") or {}, **{k: entry[k] for k in SHORT_SETTINGS if k in entry})
        if settings:
            fields["specific_settings"] = settings
        key = (fields["project"], fields["name"])
        if key in result:
            raise ValueError(f"monitor {i}: {key[1]} appears twice in project {key[0]}")
        result[key] = fields
    return result


def changes_of(monitor, fields):
    """The fields of the file that differ; settings key by key, the other settings of the monitor stay."""
    changes = {k: v for k, v in fields.items() if k not in ("specific_settings", "type") and monitor.get(k) != v}
    have = monitor.get("specific_settings") or {}
    settings = {k: v for k, v in fields.get("specific_settings", {}).items() if have.get(k) != v}
    if settings:
        changes["specific_settings"] = settings
    return changes


def plan(doc, current, prune=False):
    """Steps that bring the account (current = GET /monitors) in line with the file, as (action, monitor, details):
    create with the new monitor, update and delete with the monitor of the server, skip with the reason."""
    want = desired(doc)
    have = {}
    for monitor in current:
        have.setdefault((monitor.get("project") or "General", monitor.get("name")), []).append(monitor)
    steps = []
    for key, fields in want.items():
        found = have.get(key, [])
        if len(found) > 1:
            steps.append(("skip", fields, f"{len(found)} monitors with this name in the project, rename all but one"))
        elif not found:
            steps.append(("create", fields, None))
        elif found[0].get("type") != fields["type"]:
            steps.append(("skip", fields, f"the type cannot change ({found[0].get('type')} -> {fields['type']}), "
                                          "delete the monitor and run again"))
        else:
            changes = changes_of(found[0], fields)
            if changes:
                steps.append(("update", found[0], changes))
    if prune:
        projects = {project for project, _ in want}
        for key, found in have.items():
            if key[0] in projects and key not in want:
                steps += [("delete", monitor, None) for monitor in found]
    return steps


def show(value):
    return json.dumps(value, ensure_ascii=False)


def describe(action, monitor, details):
    label = f"{monitor.get('project')} / {monitor.get('name')}"
    if action != "update":
        return f"{action} {label}" + (f": {details}" if details else "")
    have = monitor.get("specific_settings") or {}
    parts = [f"{k}: {show(monitor.get(k))} -> {show(v)}" for k, v in details.items() if k != "specific_settings"]
    parts += [f"{k}: {show(have.get(k))} -> {show(v)}" for k, v in details.get("specific_settings", {}).items()]
    return f"update {label}: " + "; ".join(parts)


def run(action, monitor, details):
    if action == "create":
        call("POST", "/monitors", monitor)
    elif action == "update":
        call("PATCH", "/monitors/" + quote(monitor["id"], safe=""), details)
    elif action == "delete":
        call("DELETE", "/monitors/" + quote(monitor["id"], safe=""))


def main(argv=None):
    parser = argparse.ArgumentParser(description="Create WatchCore monitors from a YAML or JSON file and keep them in sync.")
    parser.add_argument("file", help="monitors.yaml, .yml or .json")
    parser.add_argument("--apply", action="store_true", help="make the changes (without it the script only shows them)")
    parser.add_argument("--prune", action="store_true",
                        help="also delete monitors that the file does not list, in the projects of the file")
    args = parser.parse_args(argv)
    if not KEY:
        sys.exit("Set WATCHCORE_KEY to an API key (WatchCore: Settings, Integrations & API).")
    try:
        doc = load(args.file)
        steps = plan(doc, call("GET", "/monitors"), args.prune)
    except (OSError, ValueError, RuntimeError) as err:
        sys.exit(f"error: {err}")
    failed = 0
    for step in steps:
        print(describe(*step))
        if args.apply and step[0] != "skip":
            try:
                run(*step)
            except RuntimeError as err:
                failed += 1
                print(f"  failed: {err}")
    todo = sum(step[0] != "skip" for step in steps)
    if not args.apply:
        print(f"{todo} change(s), nothing done yet: run again with --apply" if todo else "Everything is in sync.")
    elif todo:
        try:  # what the server adjusted or left out (plan minimum, unknown settings)
            left = [step for step in plan(doc, call("GET", "/monitors"), args.prune) if step[0] == "update"]
        except RuntimeError as err:
            left = []
            print(f"could not check the result: {err}")
        for step in left:
            print("still differs after --apply: " + describe(*step))
    return 1 if failed else 0


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