#!/usr/bin/env python3
"""fileage - a file's age in human terms plus its birth time when the filesystem reports one.
Usage: fileage <file> [...] [--selftest] [--help]
Prints, per file: size, modified time, age in human terms ("3 days, 4 hours"),
access time, change time, and birth time (btime) when the filesystem reports
one (statx on Linux; falls back gracefully elsewhere). Also shows how much of
the file's life has passed since its last modification, as a percentage.
"""
import argparse, ctypes, os, sys, tempfile, time
from pathlib import Path

def human_age(seconds):
    seconds = int(seconds)
    if seconds < 60:
        return f"{seconds} second{'s' if seconds != 1 else ''}"
    parts = []
    for unit, div in (("year", 31557600), ("month", 2592000), ("week", 604800),
                      ("day", 86400), ("hour", 3600), ("minute", 60)):
        if seconds >= div:
            v, seconds = divmod(seconds, div)
            parts.append(f"{v} {unit}{'s' if v != 1 else ''}")
        if len(parts) == 2:
            break
    return ", ".join(parts) if parts else "0 seconds"

def btime(path):
    """Birth time via statx(2) on Linux; None when unavailable."""
    try:
        libc = ctypes.CDLL("libc.so.6", use_errno=True)
    except OSError:
        return None
    class StatxTimestamp(ctypes.Structure):
        _fields_ = [("tv_sec", ctypes.c_int64), ("tv_nsec", ctypes.c_uint32), ("__reserved", ctypes.c_int32)]
    class Statx(ctypes.Structure):
        _fields_ = [("stx_mask", ctypes.c_uint32), ("stx_blksize", ctypes.c_uint32),
                    ("stx_attributes", ctypes.c_uint64),
                    ("stx_nlink", ctypes.c_uint32), ("stx_uid", ctypes.c_uint32),
                    ("stx_gid", ctypes.c_uint32), ("stx_mode", ctypes.c_uint16),
                    ("__spare0", ctypes.c_uint16), ("stx_ino", ctypes.c_uint64),
                    ("stx_size", ctypes.c_uint64), ("stx_blocks", ctypes.c_uint64),
                    ("stx_attributes_mask", ctypes.c_uint64),
                    ("stx_atime", StatxTimestamp), ("stx_btime", StatxTimestamp),
                    ("stx_ctime", StatxTimestamp), ("stx_mtime", StatxTimestamp),
                    ("stx_rdev_major", ctypes.c_uint32), ("stx_rdev_minor", ctypes.c_uint32),
                    ("stx_dev_major", ctypes.c_uint32), ("stx_dev_minor", ctypes.c_uint32),
                    ("stx_mnt_id", ctypes.c_uint64), ("stx_dio_mem_align", ctypes.c_uint32),
                    ("stx_dio_offset_align", ctypes.c_uint32),
                    ("__spare3", ctypes.c_uint64 * 12)]
    AT_FDCWD = -100
    buf = Statx()
    ret = libc.statx(AT_FDCWD, os.fsencode(str(path)), 0, 0xFFF, ctypes.byref(buf))
    if ret != 0:
        return None
    if not (buf.stx_mask & 0x800):  # STATX_BTIME
        return None
    if buf.stx_btime.tv_sec == 0:
        return None
    return buf.stx_btime.tv_sec + buf.stx_btime.tv_nsec / 1e9

def report(p):
    st = p.stat()
    now = time.time()
    print(f"{p}")
    print(f"  size:     {st.st_size} bytes")
    print(f"  modified: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(st.st_mtime))} ({human_age(now - st.st_mtime)} ago)")
    print(f"  accessed: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(st.st_atime))} ({human_age(now - st.st_atime)} ago)")
    print(f"  changed:  {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(st.st_ctime))} ({human_age(now - st.st_ctime)} ago)")
    bt = btime(p)
    if bt is not None:
        print(f"  born:     {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(bt))} ({human_age(now - bt)} ago)")
        life = now - bt
        if life > 0:
            print(f"  untouched for {100 * (now - st.st_mtime) / life:.0f}% of its life")
    else:
        print("  born:     (filesystem does not report a birth time)")

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        f = base / "sample.txt"
        f.write_text("hello")
        old = time.time() - 90061  # 1 day, 1 hour, 1 minute, 1 second
        os.utime(f, (old, old))
        assert human_age(90061) == "1 day, 1 hour", human_age(90061)
        assert human_age(45) == "45 seconds"
        assert human_age(3600 * 24 * 400) == "1 year, 1 month", human_age(3600 * 24 * 400)
        report(f)  # must not crash even without btime
        print("selftest OK: human ages correct (90061s -> '1 day, 1 hour'), report printed")
        return 0

def main():
    ap = argparse.ArgumentParser(description="fileage - a file's age in human terms, plus birth time when available")
    ap.add_argument("files", nargs="*")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if not a.files:
        ap.print_help(); return 2
    rc = 0
    for name in a.files:
        p = Path(name)
        if not p.exists():
            print(f"fileage: {name}: no such file", file=sys.stderr); rc = 1; continue
        report(p)
    return rc

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