#!/usr/bin/env python3

import argparse
import fnmatch
import os
import sys
import time
from collections import defaultdict

import tensorflow as tf

parser = argparse.ArgumentParser()
parser.add_argument('events_filename')
parser.add_argument('--only')
args = parser.parse_args()

if not os.path.isfile(args.events_filename):
    print(f"Error: events file '{args.events_filename}' does not exist", file=sys.stderr)
    exit(1)


def find_files_matching_pattern(pattern, path):
    result = []
    for root, dirs, files in os.walk(path, followlinks=True):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result


def read_events_file(events_filename):
    events = {}
    try:
        for event in tf.train.summary_iterator(events_filename):
            for value in event.summary.value:
                if value.tag not in events:
                    events[value.tag] = []
                events[value.tag].append((event.wall_time, event.step, value.simple_value))
    except Exception as e:
        print(f"While reading '{events_filename}':", e)
    return events


last_idxs = defaultdict(lambda: 0)
while True:
    if not os.path.exists(args.events_filename):
        print(f"Error: events file '{args.events_filename}' disappeared", file=sys.stderr)
        exit(1)
    events = read_events_file(args.events_filename)
    for key in events:
        if args.only and args.only not in key:
            continue
        vals_since_last = events[key][last_idxs[key]:]
        if vals_since_last:
            print(f"{key}:")
            for val in vals_since_last:
                print(val)
        else:
            time.sleep(1.0)
        last_idxs[key] = len(events[key])

