import argparse
from pathlib import Path

SEP = "\n\n" + ("=" * 78) + "\n"  # visible separator between messages

def main():
    p = argparse.ArgumentParser(description="Concatenate .eml files into one all-emails.eml")
    p.add_argument("folder", nargs="?", default=".", help="Folder containing .eml files (default: current folder)")
    p.add_argument("--output", default="all-emails.eml", help="Output file name (default: all-emails.eml)")
    p.add_argument("--sort", choices=["name", "mtime"], default="mtime",
                   help="Sort input files by name or modification time (default: mtime)")
    args = p.parse_args()

    folder = Path(args.folder).expanduser().resolve()
    if not folder.is_dir():
        raise SystemExit(f"Not a folder: {folder}")

    emls = list(folder.glob("*.eml"))
    if not emls:
        raise SystemExit(f"No .eml files found in {folder}")

    if args.sort == "name":
        emls.sort(key=lambda x: x.name.lower())
    else:
        emls.sort(key=lambda x: x.stat().st_mtime)

    out_path = folder / args.output

    with out_path.open("wb") as out:
        for i, f in enumerate(emls, 1):
            data = f.read_bytes()

            # Ensure each message ends with a newline
            if data and not data.endswith(b"\n"):
                data += b"\n"

            out.write(data)
            # Add separator so messages don't run together
            out.write(SEP.encode("utf-8"))

    print(f"Wrote {len(emls)} emails to {out_path}")

if __name__ == "__main__":
    main()

