#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
"""Free From: an allergen-style label for a folder of source code.

Reads JS/TS, Python, Go and Rust files by text pattern and prints what the
text contains, what it does not, and what could not be read. Nothing is run,
installed or sent anywhere.
"""

import argparse
import bisect
import datetime
import hashlib
import os
import re
import sys
from collections import Counter

WIDTH = 64
LIMIT = "Text patterns only. Code built at run time is not seen."
SKIP_DIRS = (".git", "node_modules", "target", "vendor", ".venv", "venv", "__pycache__", "dist-info")
EXT_LANG = {
    ".js": "js", ".mjs": "js", ".cjs": "js", ".jsx": "js",
    ".ts": "js", ".mts": "js", ".cts": "js", ".tsx": "js",
    ".py": "py", ".go": "go", ".rs": "rs",
}
LANG_NAME = {"py": "Python", "js": "JS/TS", "go": "Go", "rs": "Rust"}
MAX_BYTES = 2 * 1024 * 1024
HEAD = 8192
MAX_LINE = 1000

RUNTIME = "Built at run time"
CATEGORIES = ("Network access", "File writes", "Subprocess calls", "Environment reads", "Telemetry libraries")

# Node builtin names: Node 22 `module.builtinModules`, written down 2026-10-14 and
# cross-checked that day against the Node names in bun's `builtinModules`.
# Names that exist only behind `node:` (node:test, node:sqlite, node:sea) are
# caught by the prefix rule instead.
NODE_LIST = ("22", "2026-10-14")
NODE_BUILTINS = frozenset("""
_http_agent _http_client _http_common _http_incoming _http_outgoing _http_server
_stream_duplex _stream_passthrough _stream_readable _stream_transform _stream_wrap
_stream_writable _tls_common _tls_wrap assert assert/strict async_hooks buffer
child_process cluster console constants crypto dgram diagnostics_channel dns
dns/promises domain events fs fs/promises http http2 https inspector
inspector/promises module net os path path/posix path/win32 perf_hooks process
punycode querystring readline readline/promises repl stream stream/consumers
stream/promises stream/web string_decoder sys timers timers/promises tls
trace_events tty url util util/types v8 vm wasi worker_threads zlib
""".split())


# Pattern tables. Python `re`, applied per line to comment-stripped text.

def py_import(names):
    return rf"^\s*import\s+(?:[\w.]+(?:\s+as\s+\w+)?\s*,\s*)*(?:{names})\b"


def py_from(names):
    return rf"^\s*from\s+(?:{names})\b"


JS_HEAD = r"(?:\bfrom|\bimport|\bimport\s*\(|\brequire\s*\()\s*"


def js_module(names):
    return JS_HEAD + rf"""['"](?:node:)?(?:{names})(?:/[^'"]*)?['"]"""


PY_NET = ("socket|socketserver|ssl|http|urllib3|requests|httpx|aiohttp|ftplib|smtplib|poplib"
          "|imaplib|telnetlib|xmlrpc|websockets|websocket|paramiko|grpc")
PY_SUB = "subprocess|pty|pexpect|plumbum"
PY_TELE = ("sentry_sdk|posthog|mixpanel|amplitude|segment|ddtrace|datadog|newrelic|rollbar|bugsnag"
           "|opentelemetry|applicationinsights|statsd")
JS_NET = r"http|https|http2|net|tls|dgram|dns|axios|got|node-fetch|undici|ws|superagent|socket\.io-client"
JS_TELE = (r"@sentry/|@amplitude/|@segment/|@datadog/|@bugsnag/|@opentelemetry/|@vercel/analytics\b"
           r"|(?:posthog-js|posthog-node|mixpanel|analytics-node|dd-trace|newrelic|rollbar|logrocket"
           r"|applicationinsights)(?=['\"`/])")
RS_TELE = "sentry|posthog_rs|opentelemetry|tracing_opentelemetry|datadog|segment|mixpanel|bugsnag|rollbar"

PATTERNS = {
    RUNTIME: {
        "py": [r"(?<![\w.])eval\s*\(", r"(?<![\w.])exec\s*\(", r"(?<![\w.])compile\s*\(",
               r"\b__import__\b", r"\bimportlib\.(?:import_module|util)\b",
               r"""\bgetattr\s*\([^,()]+,(?![^\S\n]*(?P<q>['"])[^'"\n]*(?P=q)[^\S\n]*[,)])""",
               r"\b(?:globals|locals)\s*\(\s*\)\s*\[", r"\bpickle\.loads?\b", r"\bmarshal\.loads?\b",
               r"\bCodeType\b"],
        "js": [r"(?<![\w.])eval\s*\(", r"\bnew\s+Function\s*\(", r"(?<![\w.])Function\s*\(",
               r"""\bimport\s*\(\s*[^'"`\s)]""", r"""\brequire\s*\(\s*[^'"`\s)]""",
               r"""\b(?:setTimeout|setInterval)\s*\(\s*['"]""", r"\bvm\.(?:runIn\w+|Script)\b",
               r"\b(?:globalThis|window|global|self|process)\s*\[",
               r"\bWebAssembly\.(?:instantiate|compile)\b"],
        "go": [r"\bplugin\.Open\b", r"\.MethodByName\s*\(", r"\bsyscall\.Syscall\b"],
        "rs": [r"\b(?:libloading|wasmtime|mlua|rhai|pyo3|rusty_v8|deno_core)\b", r"\bdlopen\b",
               r"\bLibrary::new\b"],
    },
    "Network access": {
        "py": [py_import(PY_NET), py_from(PY_NET), r"\burllib\.request\b",
               r"^\s*from\s+urllib\s+import\s+.*\brequest\b", r"\basyncio\.open_connection\b"],
        "js": [r"\bfetch\s*\(", r"\bXMLHttpRequest\b", r"\bnew\s+WebSocket\b", r"\bEventSource\b",
               r"\bsendBeacon\b", r"\b(?:Bun|Deno)\.(?:serve|connect|listen)\b", js_module(JS_NET)],
        "go": [],
        "rs": [r"\bstd::net\b", r"\b(?:reqwest|hyper|ureq|surf|isahc|tungstenite|tonic|actix_web|axum|tokio::net)\b"],
    },
    "File writes": {
        "py": [r"""\bopen\s*\([^)]*['"][rwxab+]*[wax+][rwxab+]*['"]""", r"""\bmode\s*=\s*['"][^'"]*[wax+]""",
               r"\.(?:write_text|write_bytes)\s*\(", r"\bshutil\.(?:copy|copy2|copyfile|copytree|move|rmtree)\b",
               r"\bos\.(?:remove|unlink|rename|replace|mkdir|makedirs|rmdir|removedirs|chmod|truncate)\b",
               r"\.(?:unlink|mkdir|rmdir|rename|touch)\s*\(", r"\btempfile\b"],
        "js": [r"\b(?:writeFile|appendFile|createWriteStream|mkdtemp|copyFile|unlink|rmdir|mkdir)(?:Sync)?\s*\(",
               r"\bfs\.(?:rm|rename|cp|truncate|chmod|symlink)(?:Sync)?\s*\(", r"\bBun\.write\s*\(",
               r"\bDeno\.(?:writeFile|writeTextFile|remove|mkdir|rename)\b"],
        "go": [r"\bos\.(?:Create|WriteFile|Remove|RemoveAll|Rename|Mkdir|MkdirAll|Truncate|Chmod|Chown|Symlink"
               r"|MkdirTemp|CreateTemp|OpenFile)\b", r"\bioutil\.(?:WriteFile|TempFile|TempDir)\b"],
        "rs": [r"\bfs::(?:write|remove_file|remove_dir|remove_dir_all|create_dir|create_dir_all|rename|copy"
               r"|hard_link|set_permissions)\b", r"\bFile::create(?:_new)?\b", r"\bOpenOptions\b"],
    },
    "Subprocess calls": {
        "py": [py_import(PY_SUB), py_from(PY_SUB),
               r"\bos\.(?:system|popen|exec[lv]p?e?|spawn[lv]p?e?|fork|posix_spawn)\b",
               r"\basyncio\.create_subprocess_"],
        "js": [js_module(r"child_process|execa|shelljs|cross-spawn"), r"\bBun\.(?:spawn|spawnSync)\b",
               r"\bDeno\.Command\b"],
        "go": [r"\bsyscall\.(?:Exec|ForkExec)\b", r"\bos\.StartProcess\b"],
        "rs": [r"\bstd::process\b", r"\bprocess::Command\b", r"\bCommand::new\b", r"\b(?:duct|xshell)\b"],
    },
    "Environment reads": {
        "py": [r"\bos\.(?:environ|getenv)\b", r"^\s*from\s+os\s+import\s+.*\b(?:environ|getenv)\b", r"\bdotenv\b"],
        "js": [r"\bprocess\.env\b", r"\bBun\.env\b", r"\bimport\.meta\.env\b", r"\bDeno\.env\b", r"\bdotenv\b"],
        "go": [r"\bos\.(?:Getenv|LookupEnv|Environ|ExpandEnv)\b", r"\bgodotenv\b"],
        "rs": [r"\benv::(?:var|vars|var_os|vars_os)\b", r"\b(?:option_)?env!\s*\(", r"\bdotenvy?\b"],
    },
    "Telemetry libraries": {
        "py": [py_import(PY_TELE), py_from(PY_TELE)],
        "js": [rf"""['"`](?:{JS_TELE})""", r"\bgtag\s*\("],
        "go": [],
        "rs": [rf"(?<![\w:])(?:{RS_TELE})::", rf"\buse\s+(?:::)?(?:{RS_TELE})\b",
               rf"\bextern\s+crate\s+(?:{RS_TELE})\b"],
    },
}

# Go categories also match on import paths (whole path, as written in the import).
GO_IMPORTS = {
    RUNTIME: [r"reflect", r"plugin"],
    "Network access": [r"net", r"net/http(?:/.*)?", r"net/rpc(?:/.*)?", r"net/smtp", r"net/textproto",
                       r"google\.golang\.org/grpc(?:/.*)?", r"golang\.org/x/net(?:/.*)?",
                       r"github\.com/gorilla/websocket"],
    "File writes": [],
    "Subprocess calls": [r"os/exec"],
    "Environment reads": [],
    "Telemetry libraries": [r"github\.com/getsentry/sentry-go(?:/.*)?", r"go\.opentelemetry\.io/.*",
                            r"github\.com/posthog/.*", r"github\.com/segmentio/analytics-go(?:/.*)?",
                            r"github\.com/DataDog/.*", r"gopkg\.in/DataDog/.*", r"github\.com/newrelic/.*",
                            r"github\.com/rollbar/.*", r"github\.com/bugsnag/.*", r"github\.com/mixpanel/.*",
                            r"github\.com/amplitude/.*"],
}

ALL_CATS = (RUNTIME,) + CATEGORIES
COMPILED = {
    lang: {cat: re.compile("|".join(f"(?:{p})" for p in PATTERNS[cat][lang])) if PATTERNS[cat][lang] else None
           for cat in ALL_CATS}
    for lang in LANG_NAME
}
# A looser copy of each table, run once over a whole file as an "anything here at
# all" test before the per-line pass. Dropping a leading assertion or the JS import
# head only lets more text match, and the one negative lookahead above never looks
# past a line break, so every per-line match is also a match here.
_LEAD = re.compile(r"^(?:\\b|\^\\s\*|\(\?<!\[\\w[.:]\]\)|\(\?<!\\w\))+")


def loosen(p):
    return _LEAD.sub("", p[len(JS_HEAD):] if p.startswith(JS_HEAD) else p)


WHOLE = {lang: {cat: re.compile("|".join(f"(?:{loosen(p)})" for p in PATTERNS[cat][lang]), re.M)
                if PATTERNS[cat][lang] else None for cat in ALL_CATS}
         for lang in LANG_NAME}
GO_COMPILED = {cat: [re.compile(p) for p in pats] for cat, pats in GO_IMPORTS.items()}


# Comment stripper. Works on text whose only line break is "\n"; it never adds
# or removes a "\n", so line numbers survive.

_CODE_RE = {
    "js": re.compile(r"[/\"'`]"),
    "go": re.compile(r"//|/\*|[\"'`]"),
    "rs": re.compile(r"//|/\*|(?<!\w)b?r#*\"|[\"']"),
    "py": re.compile(r"#|'''|\"\"\"|'|\""),
}
_CHAR_LIT = re.compile(r"'(?:\\[^'\n]{1,10}|[^'\\\n])'")
_REGEX_PREV = set("(,=:[!&|?{};")
_REGEX_WORDS = {"return", "typeof", "case", "do", "else", "in", "of", "void", "yield", "await", "delete", "throw", "new"}
_STR_END = {}


def _str_end(text, start, quote, multiline):
    """Index just past the string that opened before `start`."""
    key = (quote, multiline)
    if key not in _STR_END:
        _STR_END[key] = re.compile(r"\\[\s\S]|" + re.escape(quote) + ("" if multiline else r"|\n"))
    pos = start
    while True:
        m = _STR_END[key].search(text, pos)
        if not m:
            return len(text)
        if m.group() == quote:
            return m.end()
        if m.group() == "\n":
            return m.start()
        pos = m.end()


def _eol(text, i):
    k = text.find("\n", i)
    return len(text) if k < 0 else k


def _block_end(text, i, nest):
    if not nest:
        k = text.find("*/", i + 2)
        return len(text) if k < 0 else k + 2
    depth, pos = 0, i
    for m in re.compile(r"/\*|\*/").finditer(text, pos):
        depth += 1 if m.group() == "/*" else -1
        if depth == 0:
            return m.end()
    return len(text)


def _regex_opener(text, i):
    """A JS `/` is a possible regex when the line before it is empty or ends in an operator."""
    j = i - 1
    while j >= 0 and text[j] in " \t":
        j -= 1
    if j < 0 or text[j] == "\n" or text[j] in _REGEX_PREV:
        return True
    k = j
    while k >= 0 and (text[k].isalnum() or text[k] in "_$"):
        k -= 1
    return text[k + 1:j + 1] in _REGEX_WORDS


def _strip_py(text):
    out, i, n = [], 0, len(text)
    while i < n:
        m = _CODE_RE["py"].search(text, i)
        if not m:
            out.append(text[i:])
            break
        out.append(text[i:m.start()])
        tok = m.group()
        if tok == "#":
            i = _eol(text, m.start())
        else:
            k = _str_end(text, m.end(), tok, len(tok) == 3)
            out.append(text[m.start():k])
            i = k
    return "".join(out)


def _strip_c(text, lang):
    out, i, n = [], 0, len(text)
    while i < n:
        m = _CODE_RE[lang].search(text, i)
        if not m:
            out.append(text[i:])
            break
        j = m.start()
        out.append(text[i:j])
        c, nxt = text[j], text[j + 1:j + 2]
        if c == "/" and nxt == "/":
            out.append(" ")
            i = _eol(text, j)
        elif c == "/" and nxt == "*":
            k = _block_end(text, j, lang == "rs")
            out.append(" " + "\n" * text.count("\n", j, k))
            i = k
        elif c == "/":
            k = _eol(text, j) if _regex_opener(text, j) else j + 1
            out.append(text[j:k])
            i = k
        elif c == "'" and lang in ("go", "rs"):
            cm = _CHAR_LIT.match(text, j)
            k = cm.end() if cm else j + 1
            out.append(text[j:k])
            i = k
        elif c == "`" and lang == "go":
            k = text.find("`", j + 1)
            k = n if k < 0 else k + 1
            out.append(text[j:k])
            i = k
        elif c in "rb":
            close = '"' + "#" * m.group().count("#")
            k = text.find(close, m.end())
            k = n if k < 0 else k + len(close)
            out.append(text[j:k])
            i = k
        else:
            k = _str_end(text, j + 1, c, c == "`" or (lang == "rs" and c == '"'))
            out.append(text[j:k])
            i = k
    return "".join(out)


def strip_comments(text, lang):
    """Remove comments, keep strings, return text with the same line count."""
    norm = "\n".join(text.splitlines())
    return _strip_py(norm) if lang == "py" else _strip_c(norm, lang)


# Standard-library traces.

_PY_IMPORT = re.compile(r"^\s*import\s+(.+)")
_PY_FROM = re.compile(r"^\s*from\s+([\w.]+)\s+import\b")
_JS_SPEC = re.compile(r"""(?:\bfrom|\bimport|\brequire\s*\()\s*(['"])([^'"\n]+)\1""")
# Characters a Go import path may hold (the spec lets a compiler refuse the rest).
_GO_CH = r"[^\s!\"#$%&'()*,:;<=>?\[\\\]^`{|}]*"
_GO_IMPORT = re.compile(rf"import(?!\w)\s*(?:\(([^)]*)\)|(?:[\w.]+\s+)?(\"{_GO_CH}\"|`{_GO_CH}`))")
_GO_PATH = re.compile(rf"\"({_GO_CH})\"|`({_GO_CH})`")
_RS_PATH = re.compile(r"(?<!::)\b(std|core|alloc)::(\w+|\{)")


def py_imports(line):
    """Top-level module names imported on one Python line (relative imports left out)."""
    m = _PY_FROM.match(line)
    if m:
        return [] if m.group(1).startswith(".") else [m.group(1).split(".")[0]]
    m = _PY_IMPORT.match(line)
    if not m:
        return []
    names = []
    for item in m.group(1).split(";")[0].split(","):
        im = re.match(r"\s*([\w.]+)", item)
        if im and not im.group(1).startswith("."):
            names.append(im.group(1).split(".")[0])
    return names


def js_traces(line):
    found = set()
    for m in _JS_SPEC.finditer(line):
        spec = m.group(2)
        for prefix in ("node:", "bun:"):
            if spec.startswith(prefix):
                found.add(spec[len(prefix):])
                break
        else:
            if spec in NODE_BUILTINS:
                found.add(spec)
    return found


def go_imports(text):
    """(line number, path) for every Go import path in comment-stripped text."""
    breaks = [m.start() for m in re.finditer("\n", text)]
    out = []
    for m in _GO_IMPORT.finditer(text):
        if m.start() and (text[m.start() - 1].isalnum() or text[m.start() - 1] == "_"):
            continue
        if m.group(2):
            out.append((bisect.bisect_right(breaks, m.start(2)) + 1, m.group(2)[1:-1]))
            continue
        for p in _GO_PATH.finditer(text, m.start(1), m.end(1)):
            path = p.group(1) if p.group(1) is not None else p.group(2)
            out.append((bisect.bisect_right(breaks, p.start()) + 1, path))
    return out


def go_traces(paths, module):
    keep = set()
    for path in paths:
        first = path.split("/")[0]
        if not first or "." in first or path == "C":
            continue
        if module and (path == module or path.startswith(module + "/")):
            continue
        keep.add(path)
    return keep


def rs_traces(text):
    found = set()
    for m in _RS_PATH.finditer(text):
        root = m.group(1)
        if m.group(2) != "{":
            found.add(f"{root}::{m.group(2)}")
            continue
        depth, i, start, items = 1, m.end(), m.end(), []
        while i < len(text) and depth:
            ch = text[i]
            if ch == "{":
                depth += 1
            elif ch == "}":
                depth -= 1
            if (ch == "," and depth == 1) or depth == 0:
                items.append(text[start:i])
                start = i + 1
            i += 1
        for item in items:
            im = re.match(r"\s*(\w+)", item)
            if im and im.group(1) != "self":
                found.add(f"{root}::{im.group(1)}")
    return found


# Reading.

def banner(head):
    """First `/*!` or `@license` text in the first 8192 bytes, made safe and cut to 40 characters."""
    for line in head.decode("utf-8", "replace").splitlines():
        hits = [line.find(t) for t in ("/*!", "@license") if t in line]
        if hits:
            text = "".join(c if c.isprintable() else " " for c in line[min(hits):])
            return " ".join(text.split())[:40]
    return ""


def read_source(path, rel, lot):
    """Feed the lot and classify one source file. Returns (lines, None) or (None, (reason, detail, banner))."""
    tag = rel.encode("utf-8", "surrogateescape") + b"\0"
    try:
        size = os.stat(path).st_size
    except OSError:
        size = -1
    try:
        f = open(path, "rb")
    except OSError:
        lot.update(tag + b"\0")
        if size > MAX_BYTES:
            return None, ("too large", f"too large, {size} bytes", "")
        return None, ("unreadable", "", "")
    with f:
        lot.update(tag)
        data, total = bytearray(), 0
        try:
            while chunk := f.read(1 << 20):
                lot.update(chunk)
                total += len(chunk)
                if len(data) <= MAX_BYTES:
                    data += chunk
        except OSError:
            lot.update(b"\0")
            return None, ("unreadable", "", "")
        lot.update(b"\0" + str(total).encode() + b"\0")
    data = bytes(data)
    head = data[:HEAD]
    if size > MAX_BYTES or total > MAX_BYTES:
        return None, ("too large", f"too large, {total} bytes", banner(head))
    if b"\0" in head:
        return None, ("not text", "not text", banner(head))
    try:
        text = data.decode("utf-8-sig")
    except UnicodeDecodeError:
        return None, ("not text", "not text", banner(head))
    lines = text.splitlines()
    for no, line in enumerate(lines, 1):
        if len(line) > MAX_LINE:
            return None, ("long line", f"long line {no}, {len(line)}", banner(head))
    return lines, None


def walk(root):
    """Sorted relative paths of source files, other files, skipped folder names, local Python names."""
    sources, others, skipped, local = [], [], set(), set()
    for top, dirs, files in os.walk(root):
        keep = []
        for d in dirs:
            name = "dist-info" if d.endswith(".dist-info") else d
            if name in SKIP_DIRS:
                skipped.add(name)
            elif not os.path.islink(os.path.join(top, d)):
                keep.append(d)
                local.add(d)
        dirs[:] = sorted(keep)
        for name in files:
            full = os.path.join(top, name)
            if os.path.islink(full):
                continue
            rel = os.path.relpath(full, root).replace(os.sep, "/")
            ext = os.path.splitext(name)[1]
            if ext in EXT_LANG:
                sources.append(rel)
                if ext == ".py":
                    local.add(name[:-3])
            else:
                others.append(rel)
    return sorted(sources), sorted(others), skipped, local


def go_module(root):
    try:
        with open(os.path.join(root, "go.mod"), encoding="utf-8", errors="replace") as f:
            for line in f:
                m = re.match(r"\s*module\s+\"?([^\s\"]+)", line)
                if m:
                    return m.group(1)
    except OSError:
        pass
    return ""


def scan(root):
    sources, others, skipped, local = walk(root)
    lot = hashlib.sha256()
    hits = {cat: [0, None] for cat in ALL_CATS}
    s = {"files": 0, "lines": 0, "not_examined": [], "langs": set(), "traces": set(), "hits": hits,
         "skipped": skipped, "module": go_module(root), "local": local}
    for rel in sources:
        lang = EXT_LANG[os.path.splitext(rel)[1]]
        lines, why = read_source(os.path.join(root, rel), rel, lot)
        if lines is None:
            s["not_examined"].append((rel,) + why)
            continue
        s["files"] += 1
        s["lines"] += len(lines)
        s["langs"].add(lang)
        analyse(rel, lang, lines, s)
    s["lot"] = lot.hexdigest()[:8]
    s["not_read"] = Counter(os.path.splitext(r.rsplit("/", 1)[-1])[1] or "(none)" for r in others)
    s["not_read_total"] = len(others)
    return s


def candidates(loose, text, breaks):
    """Line numbers touched by a loose whole-file match. A per-line match the loose
    scan skipped over lies inside an earlier loose match, so its line is touched too."""
    lines = set()
    for m in loose.finditer(text):
        first = bisect.bisect_right(breaks, m.start())
        last = bisect.bisect_right(breaks, max(m.start(), m.end() - 1))
        lines.update(range(first + 1, last + 2))
    return sorted(lines)


def analyse(rel, lang, lines, s):
    stripped = strip_comments("\n".join(lines), lang).split("\n") if lines else []
    text = "\n".join(stripped)
    gimports = go_imports(text) if lang == "go" else []
    breaks = [m.start() for m in re.finditer("\n", text)]
    for cat in ALL_CATS:
        rx = COMPILED[lang][cat]
        found = {no for no in candidates(WHOLE[lang][cat], text, breaks) if rx.search(stripped[no - 1])} if rx else set()
        found |= {no for no, path in gimports if any(p.fullmatch(path) for p in GO_COMPILED[cat])}
        if found:
            entry = s["hits"][cat]
            entry[0] += len(found)
            if entry[1] is None:
                entry[1] = (rel, min(found))
    if lang == "py":
        for line in stripped:
            for name in py_imports(line):
                if name in sys.stdlib_module_names and name not in s["local"]:
                    s["traces"].add(name)
    elif lang == "js":
        for line in stripped:
            s["traces"] |= js_traces(line)
    elif lang == "go":
        s["traces"] |= go_traces([p for _, p in gimports], s["module"])
    else:
        s["traces"] |= rs_traces(text)


# Layout. A line is a list of (text, style) segments; style is None, "b", "err" or "soft".

def clean(text):
    return "".join(c if c.isprintable() else "?" for c in text)


def count(n, word):
    return f"{n} {word}" if n == 1 else f"{n} {word}s"


def cut_left(text, room):
    return text if len(text) <= room else "..." + text[-(room - 3):]


def spread(left, right):
    """Left segments, then right text ending at column 64."""
    used = sum(len(t) for t, _ in left)
    return left + [(" " * max(1, WIDTH - used - len(right)), None), (right, None)]


def location(rel, line, room):
    tail = f":{line}"
    return cut_left(clean(rel), room - len(tail)) + tail


def none_found(s, star):
    segs = [(f"None found ({count(s['files'], 'file')}, {count(s['lines'], 'line')})", None)]
    return segs + [(" ", None), ("*", "err")] if star else segs


def row(name, indent, value, bold):
    """Name zone of 24 columns, value from column 25."""
    return [(indent, None), (name, "b" if bold else None), (" " * (24 - len(indent) - len(name)), None)] + value


def contains_value(n, loc, bold, width=1):
    """Count, then at least three spaces, then file:line; counts on one label share `width`
    so the locations line up."""
    gap = "   " + " " * (width - len(str(n)))
    room = WIDTH - 24 - len(str(n)) - len(gap)
    return [(str(n), "b" if bold else None), (gap, None), (location(loc[0], loc[1], room), None)]


def footnote(r, u):
    segs = [("*", "err"), (" ", None)]
    if r:
        segs += [(str(r), "err"), (" line" if r == 1 else " lines", None), (" built at run time", None)]
    if r and u:
        segs.append((" and ", None))
    if u:
        segs += [(str(u), "err"), (" file" if u == 1 else " files", None), (" not examined", None)]
    return segs + [(" could hide this.", None)]


def reasons(not_examined):
    tally = Counter(r for _, r, _, _ in not_examined)
    parts = []
    for reason in sorted(tally):
        n = tally[reason]
        parts.append(f"{n} {reason}s" if reason == "long line" and n > 1 else f"{n} {reason}")
    return ", ".join(parts)


def stdlib_by(langs):
    names = []
    if "py" in langs:
        names.append(f"Python {sys.version_info.major}.{sys.version_info.minor} running here")
    if "js" in langs:
        names.append(f"a Node {NODE_LIST[0]} list")
    if "go" in langs:
        names.append("Go import paths")
    if "rs" in langs:
        names.append("Rust std roots")
    return f"Standard library by: {', '.join(names)}." if names else ""


def build(s, dirname, date):
    heavy, light = [("=" * WIDTH, None)], [("_" * WIDTH, None)]
    nx = s["not_examined"]
    u, d = len(nx), s["hits"][RUNTIME][0]
    star = d > 0 or u > 0
    name = clean(dirname)
    name = name if len(name) <= 54 else "..." + name[-51:]
    out = [[(LIMIT, None)], heavy, spread([("FREE FROM", "b")], name), heavy,
           spread([(f"Lot {s['lot']}", None)], f"Scanned {date}"),
           [(f"Searched: {count(s['files'], 'file')}, {count(s['lines'], 'line')}", None)]]
    if u:
        out.append([(f"Not examined: {count(u, 'file')} ({reasons(nx)})", None)])
    if s["not_read_total"]:
        top = sorted(s["not_read"].items(), key=lambda kv: (-kv[1], kv[0]))[:5]
        exts = ", ".join(f"{clean(e)} {n}" for e, n in top)
        out.append([(f"Not read: {count(s['not_read_total'], 'file')} ({exts})", None)])
    if s["skipped"]:
        out.append([(f"Dependencies not read: {', '.join(sorted(s['skipped']))}", None)])
    out.append(light)
    rt = s["hits"][RUNTIME]
    present = [c for c in CATEGORIES if s["hits"][c][0]]
    w = max(len(str(s["hits"][c][0])) for c in present + [RUNTIME])
    out.append(row(RUNTIME, "", contains_value(d, rt[1], False, w) if d else none_found(s, u > 0), True))
    out.append(light)
    absent = [c for c in CATEGORIES if not s["hits"][c][0]]
    if present:
        out.append([("CONTAINS", "b")])
        out += [row(c, "  ", contains_value(s["hits"][c][0], s["hits"][c][1], True, w), True) for c in present]
    if absent:
        out.append([("FREE FROM", "b")])
        out += [row(c, "  ", none_found(s, star), False) for c in absent]
    if (absent and star) or (not d and u):
        out.append(footnote(d, u))
    if u:
        out += [light, [("Not examined", None)]]
        for rel, reason, detail, ban in nx:
            out.append([("  " + cut_left(clean(rel), WIDTH - 2), None)])
            detail = detail or reason
            if ban and len(detail) + 2 + len(ban) <= 60:
                out.append([("    ", None), (detail + "  " + ban, "soft")])
            else:
                out.append([("    ", None), (detail, "soft")])
                if ban:
                    out.append([("    ", None), (ban, "soft")])
    out.append(light)
    by = stdlib_by(s["langs"])
    if by:
        out.append([(by, "soft")])
    traces = ", ".join(clean(t) for t in sorted(s["traces"])) or "none found"
    out.append([(f"May contain traces of: {traces}.", None)])
    return out


def wrap(segs):
    """Break a line past 64 columns at the last space that fits; continue indented by 4."""
    chars = [(c, st) for t, st in segs for c in t]
    lines, lead = [], 1
    while len(chars) > WIDTH:
        k = max((i for i in range(lead, WIDTH + 1) if chars[i][0] == " " and chars[i - 1][0] != " "),
                default=WIDTH)
        lead = 5
        head = chars[:k]
        while head and head[-1][0] == " ":
            head.pop()
        lines.append(head)
        rest = chars[k:]
        while rest and rest[0][0] == " ":
            rest.pop(0)
        chars = [(" ", None)] * 4 + rest
    lines.append(chars)
    grouped = []
    for line in lines:
        g = []
        for c, st in line:
            if g and g[-1][1] == st:
                g[-1][0] += c
            else:
                g.append([c, st])
        grouped.append([(t, st) for t, st in g])
    return grouped


BG, INK = "\x1b[48;2;252;240;221m", "\x1b[38;2;26;26;26m"  # --c-cream, --ink
STYLE = {"b": ("\x1b[1m", "\x1b[22m"), "err": ("\x1b[38;2;190;59;39m", INK),  # --error
         "soft": ("\x1b[38;2;91;91;91m", INK)}  # --ink-soft


def render(label, colour):
    out = []
    for segs in label:
        for line in wrap(segs):
            if not colour:
                out.append("".join(t for t, _ in line).rstrip())
                continue
            width = sum(len(t) for t, _ in line)
            body = "".join(STYLE[st][0] + t + STYLE[st][1] if st else t for t, st in line)
            out.append("\x1b[0m" + BG + INK + body + " " * (WIDTH - width) + "\x1b[0m")
    return "\n".join(out) + "\n"


def use_colour():
    return (sys.stdout.isatty() and "NO_COLOR" not in os.environ
            and os.environ.get("COLORTERM", "") in ("truecolor", "24bit"))


def pattern_table():
    lines = ["Free From pattern table", LIMIT,
             "Applied per line to text with comments removed. A count is a number of lines.",
             f"Node builtin list: Node {NODE_LIST[0]}, written down {NODE_LIST[1]}.",
             f"Source extensions: {' '.join(EXT_LANG)}",
             f"Folders skipped: {' '.join(SKIP_DIRS)} (and *.dist-info)", ""]
    for cat in ALL_CATS:
        lines.append(cat)
        for lang in LANG_NAME:
            lines.append(f"  {LANG_NAME[lang]}")
            lines += [f"    {p}" for p in PATTERNS[cat][lang]]
            if lang == "go":
                lines += [f"    import path {p}" for p in GO_IMPORTS[cat]]
        lines.append("")
    return "\n".join(lines)


def main(argv=None):
    ap = argparse.ArgumentParser(
        prog="free_from.py",
        description="Print an allergen-style label of what a folder of source text contains. "
                    "Nothing is run, installed or sent.")
    ap.add_argument("dir", nargs="?", default=".", help="folder to read (default: the current one)")
    ap.add_argument("--patterns", action="store_true", help="print the pattern table in use and stop")
    args = ap.parse_args(argv)
    if args.patterns:
        print(pattern_table())
        return 0
    if not os.path.isdir(args.dir):
        print(f"Not a directory: {clean(args.dir)}", file=sys.stderr)
        return 2
    root = os.path.realpath(args.dir)
    label = build(scan(root), os.path.basename(root) or root, datetime.date.today().isoformat())
    sys.stdout.write(render(label, use_colour()))
    return 0


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