#! /usr/bin/env python3
import argparse
import sys
import logging
import ntplib
from datetime import datetime

logger = logging.getLogger(__name__)

def main() -> int:
    # Handle program arguments
    ap = argparse.ArgumentParser(prog='ntp-get', description='A debugging tool for reading NTP server times.')
    ap.add_argument("hosts", help="The NTP servers to query", nargs='+')
    ap.add_argument("-f", "--format", help="The output format", choices=["unix", "iso", "human"], default="human")
    ap.add_argument("--timeout", help="The query timeout", type=float, default=0.25)
    ap.add_argument('-v', '--verbose', help='Enable verbose logging', action='store_true')
    args = ap.parse_args()

    # Configure logging
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format='%(levelname)s:	%(message)s',
    )
    
    # Figure out the longest hostname
    max_host_len = max([len(host) for host in args.hosts])
    
    # Create an NTP client
    client = ntplib.NTPClient()
    
    # Query the NTP servers
    for host in args.hosts:
        try:
            # Do query
            logger.debug(f"Querying {host}")
            response = client.request(host, timeout=args.timeout)
            dt = datetime.fromtimestamp(response.tx_time)
            logger.debug(f"Response from {host}: {dt}")
            
            # Display result
            if args.format == "iso":
                print(f"{host.rjust(max_host_len)}: {dt.isoformat()}")
            elif args.format == "unix":
                print(f"{host.rjust(max_host_len)}: {response.tx_time}")
            elif args.format == "human":
                print(f"{host.rjust(max_host_len)}: {dt.strftime('%Y-%m-%d %H:%M:%S & %fms')}")
        except Exception as e:
            logger.error(f"Failed to query {host}: {e}")

    return 0

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