#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import shutil
import json
from pathlib import Path

current_dir = os.getcwd()
print("Current Directory:", current_dir)

def usage(s=None):
    if s is not None : print(s)
    print ("Usage:\npart-lam.py file.lam-info")
    sys.exit()

def get_latest_lam_info_file(directory="."):
    """
    Find the most recently modified file with extension '.lam-info' in the given directory.
    Args:
        directory (str or Path): Directory to search in (default: current directory)
    Returns:
        Path: Path to the latest .lam-info file, or None if not found
    """
    directory = Path(directory)
    files = directory.glob("*.lam-info")  # Find all .lam-info files
    # Filter only files (not directories) and get their (file, mtime) tuples
    file_mtime = [(f, f.stat().st_mtime) for f in files if f.is_file()]
    if not file_mtime:
        return None  # No .lam-info files found
    # Return the file with the latest (max) modification time
    latest_file = max(file_mtime, key=lambda x: x[1])[0]
    return latest_file




if len(sys.argv)<2 : 
    fname = get_latest_lam_info_file()
    print("No input file specified...")
    print("But I've found this file, which is the latest one:")
    print(fname)
    answ = input("Do you want to combine it?")
    if (answ in ["","Y","y"]) :
        fname = str(fname)
    else :
        usage()
else :        
    fname = sys.argv[1]

if not (os.path.isfile(fname)) : usage("File not found '%s'"%fname)

info = open(fname, "r").read()
info = json.loads(info)
print(info["files"])
out_file = fname[:-5]
with open(out_file, 'wb') as outfile:  # Open in binary write mode
        for f in info["files"] :
            print("Add file %s..."%f)
            with open(f, 'rb') as infile:  # Open in binary read mode
                shutil.copyfileobj(infile, outfile)
print("Done")