#!/usr/bin/env python3.6
print("# pip3.6 install azure-cli --user ")
import os
import sys
import datetime
import pytz
from collections import OrderedDict

from azure.cli.core import get_default_cli
#from azhelper import az_cli
from pprint import pprint as pp

def az_cli (args, debug = False):
    ''' args list or string '''
    if isinstance(args, str):
        args = args.split()
    cli = get_default_cli()
    if debug:
        cli.invoke(args)
    else:
        cli.invoke(args, out_file = open(os.devnull, 'w'))

    if cli.result.result:
        return cli.result.result
    elif cli.result.error:
        print(f"Got cli.result.error: {cli.result.error}")
        raise cli.result.error
    return list() # was True

vm_ids = list()
vm_info_by_region = dict()
print(f"got  {len(vm_ids)}vm's, Now vm list ...")
for azsub in [ "Infrastructure", "Prod", "Non-Prod" ]:
    print(f"... az vm list --subscription '{azsub}' ...\r" , end ="")
    #azr = az_cli( ["vm", "list", "--subscription", azsub, "-o", "json"] )
    azr = az_cli( ["vm", "list", "--subscription", azsub, "--query", "[].id", "-o", "tsv"] )
    print(f"vm's: {azsub:<18}, {len(azr)} {' '*20}")
    #print(f"azr={azr}")
    vm_ids.extend( azr )

    cmd = ["vm", "show","-o", "json", "--show-details", "--ids" ]
    cmd.extend( azr )
    print(f"... az vm show --show-details --ids {len(azr)} ...\r" , end ="")
    azr2 = az_cli(cmd )
    if len(azr) == 1:
        #print("azr len =1: azr2:",azr2)
        azr3 = list()
        azr3.append(azr2) #Put single dict in list
        azr2 = azr3
    #pp(azr2)
    for vm in azr2:
        #print("__vm__top") ; pp(vm) ; print("__vm__bottom")
        print( f" 1x {vm['hardwareProfile']['vmSize']:<15}, {vm['location']}, {vm['resourceGroup']}, "+
                f"State:\"{vm['powerState']}\", pubIp:{vm['publicIps']}, "
                )
        # make sure w
        vm_info_by_region.setdefault(vm['location'], dict() )
        tmp_count = vm_info_by_region[vm['location']].setdefault(vm['hardwareProfile']['vmSize'],0)
        vm_info_by_region[vm['location']][vm['hardwareProfile']['vmSize']] = tmp_count + 1

print(f"got  {len(vm_ids)} non k8s vm's")
#
for azsub in [ "Infrastructure", "Prod", "Non-Prod" ]:
    #az vmss list --subscription "Prod"
    print(f"... az vmss list --subscription '{azsub}' ...\r" , end ="")
    azr = az_cli( ["vmss", "list", "--subscription", azsub, "-o", "json" ] )
    print(f"vmss k8s found: '{azsub}'{' '*(18-len(azsub))}, {len(azr)} size:{sys.getsizeof(azr)} {' '*20}")
    for vmss in azr:
        print(f" {vmss['sku']['capacity']}x {vmss['sku']['name']:<15}, {vmss['location']},"+
              f" vmss:{vmss['name']}, {vmss['resourceGroup']},"+
              f" \"{azsub}\", State:{vmss['provisioningState']}"
             )
        vm_info_by_region.setdefault(vmss['location'], dict() )
        tmp_count = vm_info_by_region[vmss['location']].setdefault(vmss['sku']['name'],0)
        vm_info_by_region[vmss['location']][vmss['sku']['name']] = tmp_count + vmss['sku']['capacity']

#2020-01 az reservations reservation-order list  still beta with errors.
reservations = {
                "southeastasia": "3 x B4ms - VM_RI_SEA_20200128_3xB4ms till 2023-01-27",
                "australiaeast": "10 x B4ms - VM_RI_AEA_20200414_10xB4ms till  $87.77/pm/pvm 62% saving",
                "westus2":       "2 x B4ms - VM_RI_20200207_WUS2_2xB4ms till 2023",
                }
                #westus2 2xB4ms TODAY'S CHARGE 138.26 NZD  ,  TOTAL COST 4,977.36 NZD
print("Got vm info.")
# tz = datetime.timezone.utc
tz = pytz.timezone('Pacific/Auckland')
ft = "%Y-%m-%dT%H:%M:%S%z"
t = datetime.datetime.now(tz=tz).strftime(ft)
print()
print(f"== Summary {t} ==")
count_total = 0
for region,models in OrderedDict(sorted( vm_info_by_region.items() )).items():
    print(f"Region: \"{region}\"")
    count_region = 0
    for model,count in OrderedDict(sorted( models.items() )).items():
        print(f"{' '*10} {count} x {model}")
        count_region += count
    print(f"{' '*6}= {count_region} in \"{region}\"" )
    if region in reservations:
        print(f"{' '*5}RI {reservations[region]}")
    print()
    count_total += count_region
print(f"{' '*1}{count_total} total servers in azure (+ mongoDB atlas billed seperately)" )
print()
print("The End.")



