#!/usr/bin/env python3
# metaread — file metadata in one view: type, size, times, permissions, owner, xattrs, magic bytes and hashes.
# Usage: metaread [--json] file [...]
"""metaread: everything about a file on one screen. `stat` gives you times,
`file` gives you type, `getfattr` gives you xattrs, `sha256sum` gives you a
hash — metaread runs all of them at once, adds magic-byte identification and
a human-readable size, and can emit JSON for scripts."""
import argparse, hashlib, json, os, pwd, grp, stat, sys

MAGIC = [(b"\x89PNG", "PNG image"), (b"\xff\xd8\xff", "JPEG image"), (b"GIF8", "GIF image"),
         (b"%PDF", "PDF document"), (b"PK\x03\x04", "ZIP archive"), (b"\x1f\x8b", "gzip data"),
         (b"\x7fELF", "ELF executable"), (b"#!/", "script (shebang)"), (b"\xff\xfe", "UTF-16LE text"),
         (b"\xef\xbb\xbf", "UTF-8 text with BOM"), (b"SQLite format 3", "SQLite database"),
         (b"\x25\x21", "PostScript"), (b"ID3", "MP3 audio"), (b"OggS", "Ogg media")]

def human(n):
    for u in ("B", "KiB", "MiB", "GiB", "TiB"):
        if abs(n) < 1024 or u == "TiB": return f"{n:.1f}{u}" if u != "B" else f"{n}B"
        n /= 1024.0

def read_meta(path):
    st = os.lstat(path)
    import datetime
    def ts(t): return datetime.datetime.fromtimestamp(t).strftime("%Y-%m-%d %H:%M:%S") if t else "-"
    with open(path, "rb") as f: head = f.read(16)
    magic = next((d for m, d in MAGIC if head.startswith(m)), "unknown")
    if magic == "unknown":
        try:
            head.decode("utf-8"); magic = "UTF-8 text (probable)"
        except UnicodeDecodeError: magic = "binary (unknown)"
    xattrs = {}
    try:
        for name in os.listxattr(path, follow_symlinks=False):
            try: xattrs[name] = os.getxattr(path, name, follow_symlinks=False)[:60].decode("utf-8", "replace")
            except OSError: pass
    except (OSError, AttributeError): pass
    h = hashlib.sha256()
    if stat.S_ISREG(st.st_mode):
        with open(path, "rb") as f:
            for c in iter(lambda: f.read(65536), b""): h.update(c)
    return {
        "path": path, "type": magic, "size": st.st_size, "size_human": human(st.st_size),
        "mode": oct(stat.S_IMODE(st.st_mode)), "mode_human": stat.filemode(st.st_mode),
        "uid": st.st_uid, "user": pwd.getpwuid(st.st_uid).pw_name if st.st_uid in [p.pw_uid for p in pwd.getpwall()] else str(st.st_uid),
        "gid": st.st_gid, "group": grp.getgrgid(st.st_gid).gr_name,
        "mtime": ts(st.st_mtime), "atime": ts(st.st_atime), "ctime": ts(st.st_ctime),
        "birthtime": ts(getattr(st, "st_birthtime", 0)) if getattr(st, "st_birthtime", 0) else "n/a",
        "inode": st.st_ino, "links": st.st_nlink, "device": st.st_dev,
        "symlink_target": os.readlink(path) if os.path.islink(path) else None,
        "xattrs": xattrs, "sha256": h.hexdigest() if stat.S_ISREG(st.st_mode) else None,
    }

def show(path, as_json=False):
    if not os.path.lexists(path):
        print(f"metaread: {path}: no such file", file=sys.stderr); return 1
    m = read_meta(path)
    if as_json:
        print(json.dumps(m, indent=2)); return 0
    print(f"== {m['path']} ==")
    print(f"  type:        {m['type']}")
    print(f"  size:        {m['size']} bytes ({m['size_human']})")
    print(f"  mode:        {m['mode_human']} ({m['mode']})   owner: {m['user']}:{m['group']} ({m['uid']}:{m['gid']})")
    print(f"  modified:    {m['mtime']}   accessed: {m['atime']}   changed: {m['ctime']}   born: {m['birthtime']}")
    print(f"  inode:       {m['inode']}   links: {m['links']}   device: {m['device']}")
    if m["symlink_target"]: print(f"  symlink ->   {m['symlink_target']}")
    print(f"  xattrs:      {m['xattrs'] if m['xattrs'] else 'none'}")
    if m["sha256"]: print(f"  sha256:      {m['sha256']}")
    return 0

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        p = os.path.join(d, "f.txt"); open(p, "w").write("hello\n")
        os.chmod(p, 0o644)
        m = read_meta(p)
        assert m["size"] == 6 and m["mode"] == "0o644" and m["sha256"]
        assert show(p, as_json=True) == 0
    print("metaread selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Show all file metadata in one view: type, size, times, permissions, xattrs, hash.")
    ap.add_argument("files", nargs="*", help="file(s) to inspect")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    if not a.files: ap.error("need at least one file")
    return max(show(p, a.json) for p in a.files)

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