#!/usr/bin/env python3
"""
Licensa offline codebase inventory (v1). https://licensa.co/inventory/

Counts files and lines per language in a local copy of a codebase and writes
an aggregate JSON report to stdout.

What it does NOT do:
  - no network access, no upload, no telemetry
  - no execution of your code, no build, no test run, no child process
  - no reading of version-control history
  - no file names, paths, identifiers or code excerpts in the output

Usage (Python 3.8+, Linux or macOS):
  python3 -I -S inventory.py /absolute/path/to/local/copy > licensa-inventory.json

Review the JSON before sending it. Only counts and fixed labels are emitted.
Licence: MIT. You may read, audit and modify this file freely.
"""
import json
import os
import stat
import sys
import time

SCHEMA = "licensa.inventory.v1"

# extension -> language label (fixed vocabulary, never taken from your files)
LANG = {}
for label, exts in {
    "c": ".c", "c_embedded_sql": ".ec .pc .sqc", "cpp": ".cpp .cc .cxx .c++",
    "c_cpp_headers": ".h .hh .hpp .hxx .inl", "csharp": ".cs", "java": ".java",
    "kotlin": ".kt .kts", "scala": ".scala", "go": ".go", "rust": ".rs",
    "python": ".py", "ruby": ".rb", "php": ".php", "javascript": ".js .jsx .mjs .cjs",
    "typescript": ".ts .tsx", "swift": ".swift", "objective_c": ".m .mm",
    "dart": ".dart", "elixir": ".ex .exs", "erlang": ".erl", "haskell": ".hs",
    "clojure": ".clj .cljs", "fsharp": ".fs .fsx", "vb": ".vb .bas .frm .cls",
    "delphi_pascal": ".pas .dpr", "cobol": ".cob .cbl .cpy", "fortran": ".f .f90 .f95",
    "abap": ".abap", "rpg": ".rpg .rpgle", "perl": ".pl .pm", "lua": ".lua", "r": ".r",
    "sql": ".sql .plsql .pks .pkb", "shell": ".sh .bash .zsh", "powershell": ".ps1",
    "qt_ui": ".ui", "html_templates": ".html .htm .vue .svelte .twig .jinja",
    "css": ".css .scss .sass .less", "docs_markdown": ".md .rst .adoc",
}.items():
    for ext in exts.split():
        LANG[ext] = label

SKIP_DIRS = {
    "node_modules", "vendor", "vendors", "third_party", "third-party", "thirdparty",
    "external", "extern", "deps", "bower_components", "packages", "build", "builds",
    "dist", "out", "target", "bin", "obj", "generated", "gen", "coverage", "__pycache__",
    "venv", ".venv", "env", "site-packages", "pods", "carthage", "backup", "backups",
    "dumps", "fixtures", "testdata", "test-data",
}
TEST_DIRS = {"test", "tests", "testing", "spec", "specs", "__tests__", "unittests", "integration_tests", "e2e"}
BUILD_FILES = {
    "makefile": "make", "gnumakefile": "make", "cmakelists.txt": "cmake", "meson.build": "meson",
    "configure.ac": "autotools", "pom.xml": "maven", "build.gradle": "gradle",
    "build.gradle.kts": "gradle", "package.json": "npm", "pyproject.toml": "python",
    "setup.py": "python", "requirements.txt": "python", "cargo.toml": "cargo", "go.mod": "go",
    "gemfile": "bundler", "composer.json": "composer", "build.sbt": "sbt", "mix.exs": "mix",
    "pubspec.yaml": "dart", "dockerfile": "docker",
}
BUILD_SUFFIX = {".pro": "qmake", ".pri": "qmake", ".sln": "visual_studio",
                ".csproj": "dotnet", ".vbproj": "dotnet", ".vcxproj": "visual_studio", ".dpr": "delphi"}
LIMITS = {"entries": 500000, "depth": 40, "bytes_per_file": 16 * 1024 ** 2,
          "total_bytes": 16 * 1024 ** 3, "seconds": 900}


def build_kind(name):
    if name in BUILD_FILES:
        return BUILD_FILES[name]
    return BUILD_SUFFIX.get(os.path.splitext(name)[1])


def is_test_name(name):
    stem = os.path.splitext(name)[0]
    return (stem.startswith(("test_", "tst_")) or stem.endswith(("_test", "_tests", "_spec", ".test", ".spec"))
            or stem in ("test", "tests"))


def count_lines(path, size, deadline):
    """Return (lines, issue). Reads bytes only, never interprets content."""
    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
    fd = os.open(path, flags)
    try:
        if not stat.S_ISREG(os.fstat(fd).st_mode):
            return 0, "special"
        lines, last, read = 0, b"", 0
        while True:
            if time.monotonic() > deadline:
                return 0, "time"
            chunk = os.read(fd, 1 << 18)
            if not chunk:
                break
            read += len(chunk)
            if b"\0" in chunk:
                return 0, "binary"
            lines += chunk.count(b"\n")
            last = chunk[-1:]
        if read != size:
            return 0, "changed"
        return lines + (1 if last and last != b"\n" else 0), None
    finally:
        os.close(fd)


def scan(root):
    report = {
        "schema": SCHEMA,
        "status": "complete",
        "method": "physical_lines_including_blank_and_comments",
        "languages": {},
        "totals": {"files": 0, "lines": 0},
        "test_candidates": {"files": 0, "method": "file_or_directory_name_only"},
        "build_files": {},
        "history": "not_read",
        "execution": "none",
        "network": "none",
        "skipped": {"excluded_dirs": 0, "hidden": 0, "links_or_special": 0, "too_large": 0,
                    "binary": 0, "unreadable_or_changed": 0, "other_files": 0, "depth_limit": 0},
        "limits": LIMITS,
        "stop_reason": None,
    }
    sk = report["skipped"]
    deadline = time.monotonic() + LIMITS["seconds"]
    root_dev = os.lstat(root).st_dev
    seen = consumed = 0
    stack = [(root, 0, False)]
    while stack:
        path, depth, in_tests = stack.pop()
        try:
            entries = list(os.scandir(path))
        except OSError:
            sk["unreadable_or_changed"] += 1
            continue
        for e in entries:
            seen += 1
            if seen > LIMITS["entries"]:
                report["stop_reason"] = "entry_limit"
                break
            if time.monotonic() > deadline:
                report["stop_reason"] = "time_limit"
                break
            name = e.name.lower()
            if name.startswith("."):
                sk["hidden"] += 1
                continue
            try:
                st = e.stat(follow_symlinks=False)
            except OSError:
                sk["unreadable_or_changed"] += 1
                continue
            if stat.S_ISLNK(st.st_mode) or st.st_dev != root_dev:
                sk["links_or_special"] += 1
                continue
            if stat.S_ISDIR(st.st_mode):
                if name in SKIP_DIRS or name.startswith(("build-", "cmake-build-")):
                    sk["excluded_dirs"] += 1
                elif depth >= LIMITS["depth"]:
                    sk["depth_limit"] += 1
                else:
                    stack.append((e.path, depth + 1, in_tests or name in TEST_DIRS))
                continue
            if not stat.S_ISREG(st.st_mode):
                sk["links_or_special"] += 1
                continue
            bk = build_kind(name)
            if bk:
                report["build_files"][bk] = report["build_files"].get(bk, 0) + 1
            ext = os.path.splitext(name)[1]
            lang = LANG.get(ext)
            if lang is None:
                if not bk:
                    sk["other_files"] += 1
                continue
            if st.st_size > LIMITS["bytes_per_file"]:
                sk["too_large"] += 1
                continue
            if consumed + st.st_size > LIMITS["total_bytes"]:
                report["stop_reason"] = "byte_limit"
                break
            consumed += st.st_size
            try:
                n, issue = count_lines(e.path, st.st_size, deadline)
            except OSError:
                sk["unreadable_or_changed"] += 1
                continue
            if issue == "time":
                report["stop_reason"] = "time_limit"
                break
            if issue == "binary":
                sk["binary"] += 1
                continue
            if issue:
                sk["unreadable_or_changed"] += 1
                continue
            slot = report["languages"].setdefault(lang, {"files": 0, "lines": 0})
            slot["files"] += 1
            slot["lines"] += n
            report["totals"]["files"] += 1
            report["totals"]["lines"] += n
            if in_tests or is_test_name(name):
                report["test_candidates"]["files"] += 1
        if report["stop_reason"]:
            break
    report["languages"] = dict(sorted(report["languages"].items(), key=lambda kv: -kv[1]["lines"]))
    if report["stop_reason"] or sk["unreadable_or_changed"] or sk["too_large"] or sk["depth_limit"]:
        report["status"] = "partial"
    return report


def main(argv):
    if len(argv) != 2 or argv[1] in ("-h", "--help"):
        print(__doc__.strip())
        return 0 if len(argv) == 2 else 2
    root = argv[1]
    if os.name != "posix":
        print(json.dumps({"schema": SCHEMA, "status": "error", "error": "linux_or_macos_required"}))
        return 2
    if not os.path.isabs(root) or not os.path.isdir(root) or os.path.islink(root):
        print(json.dumps({"schema": SCHEMA, "status": "error", "error": "absolute_directory_path_required"}))
        return 2
    try:
        report = scan(root)
    except Exception:
        report = {"schema": SCHEMA, "status": "error", "error": "inventory_failed"}
    print(json.dumps(report, indent=2))
    return 2 if report["status"] == "error" else 0


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