"""Checks for free_from.py. Plain asserts; run with `uv run python test_free_from.py`.

Every folder here is a throwaway test input built in a temp directory to exercise
the scanner. None of it is shown anywhere as a result.
"""

import os
import subprocess
import sys
import tempfile

import free_from as ff

TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "free_from.py")
LIMIT = "Text patterns only. Code built at run time is not seen."


def make(files):
    root = tempfile.mkdtemp(prefix="ff-")
    for rel, body in files.items():
        path = os.path.join(root, rel)
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "wb") as f:
            f.write(body if isinstance(body, bytes) else body.encode())
    return root


def label(files_or_root, env=None):
    root = files_or_root if isinstance(files_or_root, str) else make(files_or_root)
    run = subprocess.run([sys.executable, TOOL, root], capture_output=True, text=True,
                         env={**os.environ, **(env or {})})
    assert run.returncode == 0, run.stderr
    return run.stdout


def rows(out):
    return {line[:24].strip(): line[24:] for line in out.splitlines() if len(line) > 24 and line[:2] in ("  ", "Bu")}


def contains(out, cat):
    block = out.split("\nCONTAINS\n")[1].split("\nFREE FROM\n")[0] if "\nCONTAINS\n" in out else ""
    return cat in block


def test_categories_per_language():
    cases = [
        ("a.py", "import os, socket\n", "Network access", "a.py:1"),
        ("a.py", "import os, sys\n", "Network access", None),
        ("a.py", "from subprocess import run as r\nr(['true'])\n", "Subprocess calls", "a.py:1"),
        ("a.py", "x = os.environ['HOME']\n", "Environment reads", "a.py:1"),
        ("a.py", "import sentry_sdk\n", "Telemetry libraries", "a.py:1"),
        ("a.py", "with open(p, 'w') as f:\n    pass\n", "File writes", "a.py:1"),
        ("a.py", "from urllib.parse import quote\n", "Network access", None),
        ("a.js", "const x = 1;\nawait fetch(u);\n", "Network access", "a.js:2"),
        ("a.ts", "import cp from 'node:child_process';\n", "Subprocess calls", "a.ts:1"),
        ("a.mjs", "import * as S from '@sentry/node';\n", "Telemetry libraries", "a.mjs:1"),
        ("a.js", "fs.writeFileSync(p, d);\n", "File writes", "a.js:1"),
        ("a.go", 'package a\nimport (\n\t"fmt"\n\t"net/http"\n)\n', "Network access", "a.go:4"),
        ("a.go", 'package a\nimport "net/url"\n', "Network access", None),
        ("a.go", 'package a\nimport ("fmt"; "os/exec")\n', "Subprocess calls", "a.go:2"),
        ("a.go", "package a\nfunc f() { os.Getenv(\"X\") }\n", "Environment reads", "a.go:2"),
        ("a.rs", "use std::net::TcpStream;\n", "Network access", "a.rs:1"),
        ("a.rs", "fn main() { let _ = std::env::args(); }\n", "Environment reads", None),
        ("a.rs", "fn main() { std::fs::write(\"x\", b\"y\"); }\n", "File writes", "a.rs:1"),
    ]
    for name, body, cat, where in cases:
        out = label({name: body})
        if where:
            assert contains(out, cat), (name, body, out)
            assert rows(out)[cat].endswith(where), (name, body, rows(out)[cat])
        else:
            assert not contains(out, cat), (name, body, out)


def test_runtime_and_negatives():
    for body in ['getattr(o, "x")\ngetattr(o, "n", None)\n', 'import re\nP = re.compile("x")\n',
                 "model.eval()\n"]:
        out = label({"a.py": body, "b.py": "x = 1\n"})
        assert "*" not in out, (body, out)
    for body in ["getattr(o, name)\n", "x = eval(s)\n", 'getattr(os, "sys" + "tem")("true")\n']:
        out = label({"a.py": body, "b.py": "x = 1\n"})
        assert rows(out)["Built at run time"].startswith("1   a.py:1"), (body, out)
    js = label({"a.js": "const m = await import(name);\nrequire('fs');\n"})
    assert rows(js)["Built at run time"].startswith("1   a.js:1"), js
    go = label({"a.go": 'package a\nimport "reflect"\n'})
    assert rows(go)["Built at run time"].startswith("1   a.go:2"), go


def test_comment_stripper():
    cases = [
        ("py", "x = 1  # fetch\ny = '#not'  # c\n", "x = 1  \ny = '#not'  "),
        ("py", 's = """a\n# kept\n"""  # gone\n', 's = """a\n# kept\n"""  '),
        ("py", "s = 'it\\'s'  # c\n", "s = 'it\\'s'  "),
        ("js", "a(); // c\nb(); /* x\ny */ c();\n", "a();  \nb();  \n c();"),
        ("js", "const s = \"it's\"; // c\n", "const s = \"it's\";  "),
        ("js", "const q = 'unterminated\nfetch(x); // c\n", "const q = 'unterminated\nfetch(x);  "),
        ("js", "const t = `a\n// kept\n`; // c\n", "const t = `a\n// kept\n`;  "),
        ("js", 'const r = /a\\//; fetch("x"); // kept\n', 'const r = /a\\//; fetch("x"); // kept'),
        ("js", "const q = a / b; // fetch(\"x\")\n", "const q = a / b;  "),
        ("rs", "/* a /* b */ c */ x\n", "  x"),
        ("rs", "fn f<'a>(s: &'a str) {} // c\n", "fn f<'a>(s: &'a str) {}  "),
        ("rs", "let c = '\"'; // c\n", "let c = '\"';  "),
        ("rs", 'let s = r#"a "// b"#; // c\n', 'let s = r#"a "// b"#;  '),
        ("rs", 'let s = "a\n// kept\n"; // c\n', 'let s = "a\n// kept\n";  '),
        ("go", "x := '\\n' // c\ny := `a\\` // c\n", "x := '\\n'  \ny := `a\\`  "),
    ]
    for lang, src, want in cases:
        got = ff.strip_comments(src, lang)
        assert got == want, (lang, src, got, want)
        assert len(got.split("\n")) == len(src.splitlines()), (lang, src)
    assert ff.strip_comments("a\r\nb\rc # x\n\n", "py").split("\n") == ["a", "b", "c ", ""]


def test_comments_and_strings_e2e():
    assert not contains(label({"a.py": "# import subprocess\nx = 1\n"}), "Subprocess calls")
    out = label({"a.js": '// fetch("x")\n/* process.env */\nconst y = 2;\n'})
    assert not contains(out, "Network access") and not contains(out, "Environment reads"), out
    assert rows(label({"s.js": 'const s = "fetch(";\n'}))["Network access"].endswith("s.js:1")
    assert rows(label({"r.js": 'const r = /a\\//; fetch("x");\n'}))["Network access"].endswith("r.js:1")
    assert not contains(label({"q.js": 'const q = a / b; // fetch("x")\n'}), "Network access")


def test_not_examined_and_banner():
    long_js = "/*! demo 1.0 */\n" + "x" * 1500 + "\n"
    out = label({"m.js": long_js, "x.py": b"a = 1\x00\n", "ok.py": "x = 1\n"})
    assert "Not examined: 2 files (1 long line, 1 not text)" in out, out
    assert "    long line 2, 1500  /*! demo 1.0 */\n" in out, out
    assert "  x.py\n    not text\n" in out, out
    assert "Searched: 1 file, 1 line" in out, out
    free = out.split("\nFREE FROM\n")[1].split("\n* ")[0].splitlines()
    assert free and all(line.endswith(" *") for line in free), free
    assert rows(out)["Built at run time"].endswith(" *"), out
    assert "* 2 files not examined could hide this." in out, out
    out = label({"b.js": "/*! evil \x1b[31m red */\n" + "y" * 1200 + "\n"})
    assert "\x1b" not in out and "/*! evil [31m red */" in out, out
    assert ff.banner(b"x\n// @license MIT  \t and\x07more " + b"z" * 80) == "@license MIT and more " + "z" * 18
    assert "too large" in label({"big.py": "x = 1\n" * 400000})
    assert "    not text\n" in label({"u.go": b"package a\n\xff\xfe\n"})


def test_footnote_forms():
    assert ff.render([ff.footnote(1, 0)], False) == "* 1 line built at run time could hide this.\n"
    assert ff.render([ff.footnote(0, 1)], False) == "* 1 file not examined could hide this.\n"
    assert ff.render([ff.footnote(2, 1)], False) == (
        "* 2 lines built at run time and 1 file not examined could hide\n    this.\n")
    out = label({"a.py": "eval(a)\neval(b)\n", "z.py": b"\x00"})
    assert "* 2 lines built at run time and 1 file not examined could hide\n    this.\n" in out, out


def test_traces_and_stdlib_by():
    root = make({
        "a.py": "import os, sys, json.tool, requests\nimport helper\n",
        "helper.py": "x = 1\n",
        "b.js": 'import fs from "node:fs"; import x from "left-pad"\n',
        "c.go": 'package c\nimport ("fmt"; "github.com/x/y")\n',
        "d.rs": "use std::{fs, io::Read};\n",
    })
    lines = label(root).rstrip("\n").split("\n")
    assert lines[-1] == "May contain traces of: fmt, fs, json, os, std::fs, std::io, sys.", lines[-1]
    major = f"{sys.version_info.major}.{sys.version_info.minor}"
    want = f"Standard library by: Python {major} running here, a Node 22 list, Go import paths, Rust std roots."
    assert lines[-3] + " " + lines[-2][4:] == want and len(lines[-3]) <= 64, lines[-3:]
    assert lines[-3].endswith("a Node 22 list,") and lines[-2].startswith("    Go"), lines[-3:]
    single = label({"a.py": "x = 1\n"}).rstrip("\n").split("\n")
    assert single[-2] == f"Standard library by: Python {major} running here." and single[-1] == (
        "May contain traces of: none found."), single[-2:]
    assert ff.go_imports('import (\n\t"fmt"\n\tf "os"\n\t_ "embed"\n)') == [(2, "fmt"), (3, "os"), (4, "embed")]
    assert ff.go_imports('import ("fmt"; . "strings")') == [(1, "fmt"), (1, "strings")]
    assert ff.go_imports('import ("a b"; "net/http")') == [(1, "net/http")]
    assert ff.go_traces(["fmt", "C", "ex.com/m", "mod/sub", "mod", "/abs", "./rel", ""], "mod") == {"fmt"}
    assert ff.rs_traces("use std::{io::{self, Read}, fs};\nlet x = core::mem::swap;") == {
        "std::io", "std::fs", "core::mem"}
    assert ff.py_imports("import a as x, b.c") == ["a", "b"] and ff.py_imports("from .x import y") == []


def test_widths():
    v = "".join(t for t, _ in ff.row("File writes", "  ", ff.none_found({"files": 1234, "lines": 123456}, True), False))
    assert v == "  File writes           None found (1234 files, 123456 lines) *" and len(v) == 63, v
    for text in ("May contain traces of: " + "x" * 150 + ".", "a " + "y" * 70 + " b " + "z" * 61):
        out = ff.render([[(text, None)]], False).splitlines()
        assert all(len(line) <= 64 for line in out), out
        assert "".join(out).replace(" ", "") == text.replace(" ", ""), out
    root = make({"a.py": "import socket\n" + "eval(x)\n" * 3})
    deep = os.path.join(root, "d" * 70)
    os.mkdir(deep)
    with open(os.path.join(deep, "n.py"), "w") as f:
        f.write("x = 1\n")
    out = label(deep)
    title = out.splitlines()[2]
    assert title.endswith("..." + "d" * 51) and len(title) == 64, title
    for out in (label(root), label({"a" * 90 + ".py": "import socket\n", "z.py": b"\0"})):
        assert all(len(line) <= 64 for line in out.splitlines()), out
        assert not any(line != line.rstrip() for line in out.splitlines())


def test_lot():
    root = make({"a.py": "x = 1\n", "b.go": "package b\n"})
    first = label(root)
    assert label(root) == first
    lot = first.splitlines()[4][:12]
    os.utime(os.path.join(root, "a.py"), (1, 1))
    assert label(root).splitlines()[4][:12] == lot
    with open(os.path.join(root, "a.py"), "w") as f:
        f.write("x = 2\n")
    assert label(root).splitlines()[4][:12] != lot
    if os.geteuid() != 0:
        os.chmod(os.path.join(root, "b.go"), 0)
        one, two = label(root), label(root)
        os.chmod(os.path.join(root, "b.go"), 0o644)
        assert one == two and "unreadable" in one, one


def test_cli():
    run = subprocess.run([sys.executable, TOOL, "/no/such/dir"], capture_output=True, text=True)
    assert run.returncode == 2 and run.stdout == "" and run.stderr == "Not a directory: /no/such/dir\n"
    run = subprocess.run([sys.executable, TOOL, "--patterns"], capture_output=True, text=True)
    assert run.returncode == 0 and all(c in run.stdout for c in ff.ALL_CATS)
    assert "Node builtin list: Node 22, written down 2026-10-14." in run.stdout
    out = label({"a.py": "x = 1\n"}, env={"NO_COLOR": "1", "COLORTERM": "truecolor"})
    assert out.startswith(LIMIT + "\n") and "\x1b" not in out
    words = ("safe", "clean", "secure", "passed", "trusted", "ok")
    assert not any(w in out.lower().split() for w in words)


def test_colour_render():
    s = ff.render([ff.row("Network access", "  ", ff.contains_value(1, ("c.py", 1), True), True),
                   ff.row("File writes", "  ", ff.none_found({"files": 2, "lines": 3}, True), False)], True)
    first, second = s.splitlines()
    assert "48;2;252;240;221" in first and "190;59;39" not in first and "\x1b[1mNetwork access" in first
    assert "\x1b[38;2;190;59;39m*" in second


if __name__ == "__main__":
    tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
    for t in tests:
        t()
        print(f"{t.__name__}: done")
    print(f"{len(tests)} checks ran")
