#!/usr/bin/env python

from builtins import input
import os
import sys
from argparse import ArgumentParser

from WMCore.Configuration import loadConfigurationFile
from WMCore.Services.WMStats.WMStatsWriter import WMStatsWriter

if __name__ == "__main__":

    if 'WMAGENT_CONFIG' not in os.environ:
        print("The WMAGENT_CONFIG environment variable needs to be set before this can run")
        sys.exit(1)

    wmagentConfig = loadConfigurationFile(os.environ["WMAGENT_CONFIG"])

    parser = ArgumentParser(usage="wmagent-unregister-wmstats [agent_url]")

    (options, args) = parser.parse_known_args()
    if not args:
        agentUrl = ("%s" % wmagentConfig.Agent.hostName)
    else:
        agentUrl = args[0]

    answer = input(f"Remove agent info record from wmstats for {agentUrl}? [y/n] ")
    if answer.lower() not in ["y", "yes"]:
        print("Aborting... no changes were made.")
        sys.exit(1)

    if hasattr(wmagentConfig, "General") and hasattr(wmagentConfig.General, "centralWMStatsURL"):
        wmstats = WMStatsWriter(wmagentConfig.General.centralWMStatsURL)
    else:
        print("General.centralWMStatsURL is not specified")
        sys.exit(1)

    report = wmstats.deleteDocsByIDs([agentUrl])

    print(report)
