#!/usr/bin/env python3

import sys
import json
import datetime
import argparse

def format_timestamp(ts):
    return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

def main():
    parser = argparse.ArgumentParser(description="List Tlog session metadata")
    parser.add_argument("file", help="Path to the tlog session JSON file")
    parser.add_argument("--user", help="Filter by username")
    args = parser.parse_args()

    sessions = {}

    with open(args.file, 'r') as f:
        for line in f:
            try:
                record = json.loads(line)
                rec_id = record.get('rec')
                user = record.get('user', 'unknown')

                if not rec_id:
                    continue

                if args.user and user != args.user:
                    continue

                if rec_id not in sessions:
                    timestamp = record.get('time', 0)
                    sessions[rec_id] = {
                        'time': timestamp,
                        'formatted_time': format_timestamp(timestamp),
                        'rec': rec_id,
                        'host': record.get('host', 'unknown'),
                        'user': user
                    }
            except json.JSONDecodeError:
                continue  # skip bad lines

    sorted_sessions = sorted(sessions.values(), key=lambda s: s['time'], reverse=True)

    print(f"{'Time':<20} | {'Session ID':<50} | {'Hostname':<25} | {'User'}")
    print('-' * 120)
    for sess in sorted_sessions:
        print(f"{sess['formatted_time']:<20} | {sess['rec']:<50} | {sess['host']:<25} | {sess['user']}")

if __name__ == "__main__":
    main()
