#!/usr/bin/env python3
"""linkcheck - find broken symlinks in a tree, with their targets.
Usage: linkcheck [dir] [--remove] [--json] [--selftest] [--help]
Walks a tree and lists every symlink whose target does not exist, showing
the link, its target, and whether the target is absolute or relative (plus
how long the link itself has existed, from its own mtime). --remove deletes
the broken links after listing them. Also flags links that point at another
broken link (a chain) and links forming a loop.
"""
import argparse, json, os, sys, tempfile
from pathlib import Path

def scan(root):
    broken, loops = [], []
    for p in root.rglob("*"):
        if p.is_symlink():
            try:
                target = os.readlink(p)
            except OSError:
                continue
            if not p.exists():
                # exists() follows the link; False means broken or loop
                try:
                    os.stat(p)
                    broken.append((p, target))  # stat ok but exists False: odd, treat as broken
                except OSError as e:
                    import errno
                    if e.errno == errno.ELOOP:
                        loops.append((p, target))
                    else:
                        broken.append((p, target))
    return broken, loops

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        (base / "real.txt").write_text("x")
        (base / "good.lnk").symlink_to("real.txt")
        (base / "bad.lnk").symlink_to("missing.txt")
        (base / "badabs.lnk").symlink_to("/nonexistent/target.txt")
        (base / "loop.lnk").symlink_to("loop.lnk")
        broken, loops = scan(base)
        bnames = {p.name for p, _ in broken}
        assert bnames == {"bad.lnk", "badabs.lnk"}, bnames
        assert {p.name for p, _ in loops} == {"loop.lnk"}, loops
        print("selftest OK: 2 broken links found (relative + absolute), 1 loop flagged, good link kept")
        return 0

def main():
    ap = argparse.ArgumentParser(description="linkcheck - find broken symlinks in a tree, with their targets")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--remove", action="store_true", help="delete the broken links found")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    root = Path(a.dir)
    if not root.is_dir():
        print(f"linkcheck: {a.dir}: not a directory", file=sys.stderr); return 2
    broken, loops = scan(root)
    if a.json:
        out = [{"link": str(p), "target": t, "absolute": os.path.isabs(t),
                "age_days": round((__import__("time").time() - p.lstat().st_mtime) / 86400, 1)}
               for p, t in broken]
        print(json.dumps({"broken": out, "loops": [str(p) for p, _ in loops]}, indent=2))
    else:
        if not broken and not loops:
            print("no broken symlinks"); return 0
        for p, t in broken:
            kind = "absolute" if os.path.isabs(t) else "relative"
            print(f"BROKEN {p} -> {t} ({kind})")
        for p, t in loops:
            print(f"LOOP   {p} -> {t}")
        print(f"{len(broken)} broken, {len(loops)} loop(s)")
    if a.remove and broken:
        for p, _ in broken:
            p.unlink()
        print(f"removed {len(broken)} broken link(s)")
    return 0

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