#!/usr/bin/env python3
"""Check AO's health checks. Usage: python3 check_ao.py https://ao.example.com"""
import json
import sys
import urllib.error
import urllib.request

ao = sys.argv[1].rstrip("/")
failed = []
for service in ["geo", "survey", "file", "asset-server", "toolchain", "message"]:
    url = f"{ao}/api/v1/serverstates/{service}/heartbeat"
    request = urllib.request.Request(url, headers={"User-Agent": "ao-health-check"})
    try:
        with urllib.request.urlopen(request, timeout=15) as response:
            answer = json.load(response)
        database, built = answer.get("dbConnectivity"), answer.get("builtDateTime")
        healthy = database in (None, "ok")
        print(f"{service:13} {response.status}  database {database}  built {built}")
    except urllib.error.HTTPError as error:
        healthy = False
        print(f"{service:13} {error.code}")
    except (urllib.error.URLError, TimeoutError) as error:
        healthy = False
        print(f"{service:13} no answer ({error})")
    except ValueError:
        healthy = False
        print(f"{service:13} the answer isn't a health check (a sign-in page or proxy in the way?)")
    if not healthy:
        failed.append(service)

if failed:
    print("Failed:", ", ".join(failed))
    sys.exit(1)
