#! /usr/bin/env python3

import sys
import argparse
import subprocess
from pathlib import Path

def main() -> int:
    ap = argparse.ArgumentParser(prog="mc-log-cat", description="Analyze a set of Minecraft logs")
    ap.add_argument("logs_dir", help="Path to the logs directory", type=Path)
    args = ap.parse_args()

    # Find all compressed (old) logs
    compressed_logs = list(args.logs_dir.glob("*.log.gz"))
    compressed_logs.sort()

    # Non-destructively read the contents of each archive
    log_files = []
    for file in compressed_logs:
        file_contents = subprocess.run(["gunzip", "-c", file.as_posix()], capture_output=True, text=True)
        log_files.append(file_contents.stdout)

    # Read and append the most recent log
    if args.logs_dir.joinpath("latest.log").exists():
        log_files.append(args.logs_dir.joinpath("latest.log").read_text())
    
    # Print the logs
    for log in log_files:
        print(log)

    return 0

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