import argparse
import json
from pathlib import Path
import sys
from urllib.parse import urlsplit


def configuration(endpoint):
    url = urlsplit(endpoint)
    if url.scheme != "https" or not url.hostname or url.username or url.password or url.query or url.fragment or url.path != "/metrics":
        raise ValueError("Use a credential-free HTTPS endpoint ending in /metrics")
    _ = url.port
    return {"global": {"scrape_interval": "30s", "evaluation_interval": "30s"},
            "rule_files": ["/etc/prometheus/post76.rules.yml"],
            "alerting": {"alertmanagers": [{"static_configs": [{"targets": ["alertmanager:9093"]}]}]},
            "scrape_configs": [{"job_name": "post76", "honor_labels": True, "scheme": "https", "metrics_path": "/metrics",
                                "authorization": {"type": "Bearer", "credentials_file": "/run/secrets/metrics_access_key"},
                                "tls_config": {"insecure_skip_verify": False, "server_name": url.hostname},
                                "static_configs": [{"targets": [url.netloc]}]}]}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Prepare public Prometheus configuration for a separate monitoring host")
    parser.add_argument("--endpoint", required=True)
    parser.add_argument("--destination", required=True)
    args = parser.parse_args()
    try:
        values = configuration(args.endpoint)
        with Path(args.destination).open("x") as output:
            json.dump(values, output, indent=2)
            output.write("\n")
    except (ValueError, OSError) as error:
        print("Monitoring configuration failed: " + str(error), file=sys.stderr)
        raise SystemExit(1)
