#!/usr/bin/env python3
"""Wasabi Storage Utilization special agent for Checkmk.

Queries the Wasabi Stats API for the utilization of every bucket in the
account and emits one Checkmk agent section line (JSON) per bucket. Buckets
are discovered entirely from the API response - no bucket list is configured
anywhere.
"""

import argparse
import json
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone

SECTION_HEADER = "<<<wasabi_bucket_utilization:sep(0)>>>"
PAGE_SIZE = 100  # Wasabi Stats API caps pageSize at 100; larger values return HTTP 400
OBSOLETE_AFTER_DAYS = 2  # bucket is this many days behind the newest record of the account -> obsolete
HIDE_AFTER_DAYS = 7  # ... and is no longer reported at all after this many days
MAX_PAGES = 1000  # safety stop in case the API ignores pageNum and repeats a full page


def api_get(base_url: str, path: str, params: dict, auth_header: str, timeout: int) -> list:
    """Perform a GET request against the Wasabi Stats API and return the JSON body."""
    url = f"{base_url}{path}?{urllib.parse.urlencode(params)}"
    req = urllib.request.Request(url, headers={"Authorization": auth_header})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            raw = resp.read().decode("utf-8")
    except urllib.error.HTTPError as exc:
        body = exc.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"HTTP error {exc.code} from Wasabi Stats API: {body}") from exc
    except urllib.error.URLError as exc:
        raise RuntimeError(f"Connection error to Wasabi Stats API: {exc.reason}") from exc

    try:
        data = json.loads(raw)
    except json.JSONDecodeError as exc:
        raise RuntimeError(f"Invalid JSON response from Wasabi Stats API: {exc}") from exc

    if isinstance(data, dict):
        # The list-all endpoint wraps the list as {"PageInfo": {...}, "Records": [...]}.
        for key in ("Records", "data", "records", "result", "results"):
            if key in data and isinstance(data[key], list):
                return data[key]
        raise RuntimeError(f"Unexpected response shape from Wasabi Stats API: {raw[:500]}")

    if not isinstance(data, list):
        raise RuntimeError(f"Unexpected response type from Wasabi Stats API: {raw[:500]}")

    return data


def fetch_all_records(base_url: str, auth_header: str, timeout: int) -> list:
    """Fetch all bucket utilization records across all pages.

    The Wasabi Stats API pages are ZERO-based: pageNum=0 is the first page (and the
    default when pageNum is omitted). Starting at 1 silently skips the first
    PAGE_SIZE records, which are the oldest ones (the API returns ~31 days of daily
    records sorted by time). What is left is only the tail of the list, so which
    buckets show up depends on where the page boundary falls - buckets then
    appear and vanish whenever a new daily record shifts that boundary.

    No from/to/latest filter is sent. newest_per_bucket() picks the newest record
    per bucket from the complete result.
    """
    records: list = []
    for page_num in range(MAX_PAGES):
        page = api_get(
            base_url,
            "/v1/standalone/utilizations/bucket",
            {
                "pageSize": PAGE_SIZE,
                "pageNum": page_num,
            },
            auth_header,
            timeout,
        )
        records.extend(page)
        if len(page) < PAGE_SIZE:
            break
    else:
        raise RuntimeError(
            f"Wasabi Stats API returned more than {MAX_PAGES} pages - giving up "
            "(pagination not advancing?)"
        )

    return records


def newest_per_bucket(records: list) -> dict:
    """Reduce a list of utilization records to the newest record per bucket name."""
    newest: dict = {}
    for record in records:
        bucket = record.get("Bucket")
        if not bucket:
            continue
        end_time = record.get("EndTime", "")
        current = newest.get(bucket)
        if current is None or end_time > current.get("EndTime", ""):
            newest[bucket] = record
    return newest


def _parse_end_time(value: object) -> datetime | None:
    try:
        return datetime.strptime(str(value), "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
    except ValueError:
        return None


def classify_buckets(newest: dict) -> list:
    """Return (name, record, obsolete) for every bucket that should be reported.

    A bucket whose newest record is OBSOLETE_AFTER_DAYS or more behind the newest
    record of the whole account has stopped producing data (typically: deleted) and is
    flagged obsolete. Once it is more than HIDE_AFTER_DAYS behind it is dropped, so a
    deleted bucket is shown for a limited time only. Age is measured against the API's
    own newest record, not the local clock, so an API-wide delay marks nothing obsolete.
    """
    parsed = {name: _parse_end_time(rec.get("EndTime")) for name, rec in newest.items()}
    known = [t for t in parsed.values() if t is not None]
    reference = max(known) if known else None

    result = []
    for name, record in newest.items():
        end = parsed[name]
        age_days = (reference - end).days if reference and end else 0
        if age_days > HIDE_AFTER_DAYS:
            continue
        result.append((name, record, age_days >= OBSOLETE_AFTER_DAYS))
    return result


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Wasabi Storage Utilization special agent for Checkmk"
    )
    parser.add_argument("--access-key", required=True, help="Wasabi Access Key")
    parser.add_argument("--secret-key", required=True, help="Wasabi Secret Key")
    parser.add_argument(
        "--base-url", default="https://stats.wasabisys.com", help="Wasabi Stats API base URL"
    )
    parser.add_argument("--timeout", type=int, default=30, help="Request timeout in seconds")
    args = parser.parse_args()

    auth_header = f"{args.access_key}:{args.secret_key}"

    try:
        records = fetch_all_records(args.base_url, auth_header, args.timeout)
    except RuntimeError as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1

    buckets = newest_per_bucket(records)

    print(SECTION_HEADER)
    for bucket_name, record, obsolete in classify_buckets(buckets):
        output = {
            "bucket": bucket_name,
            "region": record.get("Region"),
            "active_bytes": record.get("RawStorageSizeBytes", 0),
            "deleted_bytes": record.get("DeletedStorageSizeBytes", 0),
            "padded_bytes": record.get("PaddedStorageSizeBytes"),
            "end_time": record.get("EndTime"),
            "obsolete": obsolete,
        }
        print(json.dumps(output, ensure_ascii=False))

    return 0


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