import sys, os

import argparse

from leapseconddata import LeapSecondData
from math import ldexp
from pathlib import Path
from datetime import datetime, timezone
import secrets


class BooleanAction(argparse.Action):
    def __init__(self, option_strings, dest, nargs=None, **kwargs):
        super(BooleanAction, self).__init__(option_strings, dest, nargs=0, **kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, False if option_string.startswith('--no') else True)


def main():
    parser = argparse.ArgumentParser(prog='tai64dec', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--random', '--no-random', action=BooleanAction, default=False)
    parser.add_argument('--ns', '--no-ns', action=BooleanAction, default=True)
    args = parser.parse_args()


    leapsecond_data = LeapSecondData.from_file(Path(os.getenv('LEAPSECONDS_FILE')))

    now = datetime.now(tz=timezone.utc)

    tai_dt = leapsecond_data.to_tai(now)
    seconds = int(tai_dt.timestamp())
    seconds += int(ldexp(1, 62))
    out = seconds

    if args.ns:
        nanoseconds = int((tai_dt.timestamp() - seconds) / 1e-9)
        out = out << 32 | nanoseconds

    if args.random:
        out = out << 24 | int.from_bytes(secrets.token_bytes(3), byteorder='little', signed=False)

    print('{:d}'.format(out), file=sys.stdout)

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