#!/usr/bin/env python3
"""Script Check 0.5.1 by Load Bearing (single-file build).

Local, read-only checker for IBM Maximo automation scripts (Jython and JavaScript).
It never executes or uploads your code. Usage: python lbcheck.py <files or folders>
Run with --list-rules to see every rule. Sources: loadbearingeam.com
"""
from __future__ import annotations

__version__ = "0.5.1"

# ---- analyzer.py ----
"""Source preparation for Maximo automation scripts.

Maximo runs automation scripts in Jython (Python 2.7 syntax) or JavaScript
(Nashorn). Python 3's parser rejects some Jython syntax, so the checker works
on cleaned source lines instead of a full syntax tree, for both languages.
Each line keeps its string literals (rules need them) but loses its comments,
remembers whether it carried a comment, and knows whether it sits inside a
loop: by indentation for Python, by braces for JavaScript.
"""


import re
from dataclasses import dataclass, field
from pathlib import Path

_BLOCK_OPENER = re.compile(r":\s*$")
_LOOP_OPENER = re.compile(r"^(for|while)\b")


@dataclass
class Line:
    number: int  # 1-based line number in the original file
    raw: str  # original text without the trailing newline
    code: str  # text with comments removed and docstring content blanked
    indent: int
    in_loop: bool
    comment: bool = False  # a comment appeared on this line
    comment_text: str = ""  # the comment's text, without the marker


JS_SUFFIXES = {".js"}


def language_for(path: str) -> str:
    return "javascript" if Path(path).suffix.lower() in JS_SUFFIXES else "python"


@dataclass
class Script:
    path: str
    lines: list[Line] = field(default_factory=list)
    language: str = "python"

    @property
    def code_lines(self) -> list[Line]:
        return [line for line in self.lines if line.code.strip()]


def _strip_comments(text: str) -> tuple[list[str], list[str | None]]:
    """Remove comments and the content of triple-quoted strings, line by line.

    Single-line string literals are kept intact because several rules inspect
    them. Triple-quoted blocks (docstrings, long SQL) are replaced with empty
    quotes so that comment-like text inside them is not misread as code.
    """
    out: list[str] = []
    flags: list[bool] = []
    in_triple: str | None = None
    for raw in text.splitlines():
        has_comment = False
        result = []
        i = 0
        quote: str | None = None
        while i < len(raw):
            ch = raw[i]
            if in_triple:
                if raw.startswith(in_triple, i):
                    result.append(in_triple)
                    i += 3
                    in_triple = None
                else:
                    i += 1
                continue
            if quote:
                result.append(ch)
                if ch == "\\" and i + 1 < len(raw):
                    result.append(raw[i + 1])
                    i += 2
                    continue
                if ch == quote:
                    quote = None
                i += 1
                continue
            if raw.startswith('"""', i) or raw.startswith("'''", i):
                in_triple = raw[i : i + 3]
                result.append(in_triple)
                i += 3
                continue
            if ch in ("'", '"'):
                quote = ch
                result.append(ch)
                i += 1
                continue
            if ch == "#":
                has_comment = raw[i + 1 :].strip()
                break
            result.append(ch)
            i += 1
        out.append("".join(result).rstrip())
        flags.append(has_comment if has_comment is not False else None)
    return out, flags


def _strip_js_comments(text: str) -> tuple[list[str], list[str | None]]:
    """Remove // and /* */ comments from JavaScript, keeping string literals intact."""
    out: list[str] = []
    flags: list[bool] = []
    in_block = False
    for raw in text.splitlines():
        result = []
        comment_parts: list[str] = []
        has_comment = in_block
        i = 0
        quote: str | None = None
        while i < len(raw):
            ch = raw[i]
            if in_block:
                if raw.startswith("*/", i):
                    in_block = False
                    i += 2
                else:
                    comment_parts.append(ch)
                    i += 1
                continue
            if quote:
                result.append(ch)
                if ch == "\\" and i + 1 < len(raw):
                    result.append(raw[i + 1])
                    i += 2
                    continue
                if ch == quote:
                    quote = None
                i += 1
                continue
            if raw.startswith("//", i):
                has_comment = True
                comment_parts.append(raw[i + 2 :])
                break
            if raw.startswith("/*", i):
                in_block = True
                has_comment = True
                i += 2
                continue
            if ch in ("'", '"', "`"):
                quote = ch
            result.append(ch)
            i += 1
        out.append("".join(result).rstrip())
        flags.append("".join(comment_parts).strip(" *") if has_comment else None)
    return out, flags


_JS_STRING = re.compile(r"(['\"`])(?:\\.|(?!\1).)*\1")
_JS_LOOP_HEADER = re.compile(r"(?:^|[\s;{}])(?:for(?:\s+each)?|while)\s*\(|^do\b|\.forEach\s*\(\s*(?:function\b|\(?\w*\)?\s*=>)")
_JS_DO_WHILE_TAIL = re.compile(r"^\}\s*while\s*\(.*\)\s*;?\s*$")


def _text_after_header(bare: str) -> bool:
    """True when a statement follows the loop header's closing parenthesis on the same line."""
    m = _JS_LOOP_HEADER.search(" " + bare)
    if not m or bare.lstrip().startswith("}"):
        return False
    depth, start = 0, m.end() - 2  # the opening parenthesis is the last character the header matched
    for pos in range(max(start, 0), len(bare)):
        if bare[pos] == "(":
            depth += 1
        elif bare[pos] == ")":
            depth -= 1
            if depth == 0:
                return bool(bare[pos + 1 :].strip(" ;"))
    return False


def _parse_js(script: Script, raw_lines: list[str], cleaned: list[str], comments: list[bool]) -> None:
    stack: list[bool] = []  # one entry per open brace: True when it opened a loop body
    pending_loop = False  # a loop header without a brace yet
    for idx, (raw, code, ctext) in enumerate(zip(raw_lines, cleaned, comments), start=1):
        has_comment, ctext = ctext is not None, ctext or ""
        stripped = code.strip()
        if not stripped:
            script.lines.append(Line(idx, raw, "", 0, any(stack), has_comment, ctext))
            continue
        bare = _JS_STRING.sub('""', stripped)
        in_loop = any(stack)
        header = bool(_JS_LOOP_HEADER.search(" " + bare)) and not _JS_DO_WHILE_TAIL.match(bare)
        if header and "{" not in bare and bare.endswith(";"):
            header = False  # "while (x);" or a loop with its whole body on this line: nothing follows
            if _text_after_header(bare):
                in_loop = True  # "for (...) stmt;": the body is on this line
        loop_brace_next = header or pending_loop
        if pending_loop and not bare.startswith("{"):
            in_loop = True  # single-statement loop body
            loop_brace_next = False
        pending_loop = False
        for pos, ch in enumerate(bare):
            if ch == "{":
                stack.append(loop_brace_next)
                if loop_brace_next and bare[pos + 1 :].strip(" }"):
                    in_loop = True  # loop body continues on the header line
                loop_brace_next = False
            elif ch == "}" and stack:
                stack.pop()
        if header and "{" not in bare:
            pending_loop = True
        script.lines.append(Line(idx, raw, code, _indent_of(code), in_loop, has_comment, ctext))


def _indent_of(text: str) -> int:
    expanded = text.expandtabs(4)
    return len(expanded) - len(expanded.lstrip(" "))


def parse(text: str, path: str = "<script>", language: str | None = None) -> Script:
    script = Script(path=path, language=language or language_for(path))
    raw_lines = text.splitlines()
    if script.language == "javascript":
        cleaned, comments = _strip_js_comments(text)
        _parse_js(script, raw_lines, cleaned, comments)
        return script
    cleaned, comments = _strip_comments(text)
    # Stack of (indent, is_loop) for open blocks.
    stack: list[tuple[int, bool]] = []
    for idx, (raw, code, ctext) in enumerate(zip(raw_lines, cleaned, comments), start=1):
        has_comment, ctext = ctext is not None, ctext or ""
        if not code.strip():
            script.lines.append(Line(idx, raw, "", 0, any(l for _, l in stack), has_comment, ctext))
            continue
        indent = _indent_of(code)
        while stack and stack[-1][0] >= indent:
            stack.pop()
        in_loop = any(is_loop for _, is_loop in stack)
        stripped = code.strip()
        script.lines.append(Line(idx, raw, code, indent, in_loop, has_comment, ctext))
        if _BLOCK_OPENER.search(stripped):
            stack.append((indent, bool(_LOOP_OPENER.match(stripped))))
    return script


def load(path: str | Path) -> Script:
    p = Path(path)
    text = p.read_text(encoding="utf-8", errors="replace")
    return parse(text, str(p))

# ---- rules.py ----
"""Rules for Maximo automation scripts.

Each rule reads a parsed Script and returns Findings. Rules flag patterns that
deserve a human review before go-live; a finding is not proof of a defect.
"""


import re
from dataclasses import asdict, dataclass
from typing import Callable


SEVERITY_ORDER = {"low": 1, "medium": 2, "high": 3}


@dataclass
class Finding:
    rule_id: str
    severity: str
    path: str
    line: int
    message: str
    suggestion: str
    snippet: str = ""

    def to_dict(self) -> dict:
        return asdict(self)


Rule = Callable[[Script], list[Finding]]
RULES: list[tuple[str, str, Rule]] = []  # (rule_id, title, function)


def rule(rule_id: str, title: str):
    def register(fn: Rule) -> Rule:
        RULES.append((rule_id, title, fn))
        return fn

    return register


def _finding(script: Script, rule_id: str, severity: str, line, message: str, suggestion: str) -> Finding:
    return Finding(rule_id, severity, script.path, line.number, message, suggestion, line.raw.strip()[:160])


_STRING = re.compile(r"(['\"])((?:\\.|(?!\1).)*)\1")


def _literals(code: str) -> list[str]:
    return [m.group(2) for m in _STRING.finditer(code)]


# --- LB001 / LB002: MboSets opened through MXServer -------------------------

# Optional JavaScript declaration keyword, so "var s = ..." reads like "s = ...".
_DECL = r"^\s*(?:(?:var|let|const)\s+)?"
_SERVER_ASSIGN = re.compile(_DECL + r"(\w+)\s*=\s*MXServer\.getMXServer\(\)\s*;?\s*$")
_SET_ASSIGN = re.compile(_DECL + r"(\w+)\s*=\s*([^;=]+?)\.getMboSet\s*\(")


def _statements(code: str) -> list[str]:
    """Split a line on semicolons outside string literals, so 'var a = 1; var s = x' gives two statements."""
    parts, buf, quote, i = [], [], None, 0
    while i < len(code):
        ch = code[i]
        if quote:
            buf.append(ch)
            if ch == "\\" and i + 1 < len(code):
                buf.append(code[i + 1])
                i += 2
                continue
            if ch == quote:
                quote = None
        elif ch in "'\"`":
            quote = ch
            buf.append(ch)
        elif ch == ";":
            parts.append("".join(buf))
            buf = []
        else:
            buf.append(ch)
        i += 1
    parts.append("".join(buf))
    return [p for p in parts if p.strip()]


def _server_names(script: Script) -> set[str]:
    names = set()
    for line in script.code_lines:
        for stmt in _statements(line.code):
            m = _SERVER_ASSIGN.match(stmt)
            if m:
                names.add(m.group(1))
    return names


def _is_server_call(receiver: str, server_names: set[str]) -> bool:
    receiver = receiver.strip()
    return "MXServer.getMXServer()" in receiver or receiver in server_names


_FUNC_DEF = re.compile(r"^\s*(?:def|function)\s+(\w+)\s*\(\s*(\w+)")
# Names that say they close a set: close, _close, cleanup, closeSet, closeMboSet, closeAll,
# closeQuietly, close_set, safeClose, releaseAndClose. Not closeDialog, disclose or isClosed.
_CLOSE_SUFFIX = re.compile(r"(?:Close|Cleanup)$")


def _is_close_name(name: str) -> bool:
    if re.match(r"^_*(?:close|cleanup)(?:_?(?:mbo)?sets?|_?all|_?quietly)?$", name, re.IGNORECASE):
        return True
    if re.match(r"^\w+_(?:close|cleanup)$", name, re.IGNORECASE):
        return True
    return bool(_CLOSE_SUFFIX.search(name)) and name[0].islower()


def _function_body(script: Script, start: int) -> list[str]:
    """Code of the function defined at script.lines[start], including a body on the same line.

    JavaScript: up to the brace that closes the function. Python: the text after the colon,
    then following lines indented deeper than the def.
    """
    lines = script.lines
    first = lines[start]
    if script.language == "javascript":
        body, depth, opened = [], 0, False
        for line in lines[start:]:
            code = _STRING.sub('""', line.code)
            body.append(code)
            for ch in code:
                if ch == "{":
                    depth += 1
                    opened = True
                elif ch == "}":
                    depth -= 1
            if opened and depth <= 0:
                break
        return body
    body = [first.code.split(":", 1)[1] if ":" in first.code else ""]
    for line in lines[start + 1 :]:
        if not line.code.strip():
            continue
        if line.indent <= first.indent:
            break
        body.append(line.code)
    return body


def _close_helpers(script: Script) -> set[str]:
    """Functions defined in the script that close their first parameter inside their own body."""
    helpers = set()
    for i, line in enumerate(script.lines):
        m = _FUNC_DEF.match(line.code)
        if not m:
            continue
        name, param = m.groups()
        closes = re.compile(rf"\b{re.escape(param)}\s*\.\s*(close|cleanup)\s*\(")
        if any(closes.search(code) for code in _function_body(script, i)):
            helpers.add(name)
    return helpers


def _closed_by_helper(var: str, all_code: str, helpers: set[str]) -> bool:
    for m in re.finditer(rf"([\w.]+)\s*\(\s*{re.escape(var)}\s*[,)]", all_code):
        name = m.group(1).split(".")[-1]
        if name in helpers or _is_close_name(name):
            return True
    return False


@rule("LB001", "MboSet opened through MXServer is never closed")
def unclosed_mboset(script: Script) -> list[Finding]:
    findings = []
    servers = _server_names(script)
    helpers = _close_helpers(script)
    all_code = "\n".join(line.code for line in script.code_lines)
    for line in script.code_lines:
        for stmt in _statements(line.code):
            m = _SET_ASSIGN.match(stmt)
            if not m or not _is_server_call(m.group(2), servers):
                continue
            var = m.group(1)
            if re.search(rf"\b{re.escape(var)}\s*\.\s*(close|cleanup)\s*\(", all_code):
                continue
            if _closed_by_helper(var, all_code, helpers):
                continue
            findings.append(_finding(
                script, "LB001", "high", line,
                f"MboSet '{var}' is opened with MXServer.getMboSet but never closed.",
                f"Call {var}.close() in a finally block so database resources are released even when the script fails.",
            ))
    return findings


_SERVER_GETMBOSET = re.compile(r"MXServer\.getMXServer\(\)\s*\.\s*getMboSet\s*\(")


@rule("LB002", "MboSet opened through MXServer inside a loop")
def mboset_in_loop(script: Script) -> list[Finding]:
    findings = []
    servers = _server_names(script)
    for line in script.code_lines:
        if not line.in_loop:
            continue
        direct = _SERVER_GETMBOSET.search(line.code)
        via_var = any(re.search(rf"\b{re.escape(s)}\s*\.\s*getMboSet\s*\(", line.code) for s in servers)
        if direct or via_var:
            findings.append(_finding(
                script, "LB002", "medium", line,
                "A new MboSet is opened through MXServer inside a loop.",
                "Open the set once before the loop and reset its where clause, or use a relationship from the current record. Each set is a separate database query and a separate resource to close.",
            ))
    return findings


# --- LB003: SQL built by concatenation ---------------------------------------

_WHERE_CALL = re.compile(r"\b(setWhere|getMboSet|setQbe|setUserWhere)\s*\(")
# String joining only: "..." + x, x + "...", "..." % x, "...".format(x).
# A bare .format( is not enough: SqlFormat.format() is the safe pattern.
_CONCAT = re.compile(r"""(['"]\s*\+|\+\s*['"]|['"]\s*%\s*[\w(]|['"]\s*\.format\s*\()""")
_SQL_QUOTED_TAIL = re.compile(r"(=\s*'$|\bin\s*\(\s*'?$|\blike\s*'$)", re.IGNORECASE)
_SQL_KEYWORD_TAIL = re.compile(r"\b(where|and|or)\s*$", re.IGNORECASE)


def _looks_like_sql_fragment(lit: str) -> bool:
    if _SQL_QUOTED_TAIL.search(lit):
        return True
    return bool(_SQL_KEYWORD_TAIL.search(lit) and ("=" in lit or "'" in lit))


@rule("LB003", "Where clause built by string concatenation")
def sql_concatenation(script: Script) -> list[Finding]:
    findings = []
    for line in script.code_lines:
        if not _CONCAT.search(line.code):
            continue
        direct = _WHERE_CALL.search(line.code)
        literals = _literals(line.code)
        sql_like = any(_looks_like_sql_fragment(lit) for lit in literals)
        if direct or sql_like:
            findings.append(_finding(
                script, "LB003", "high", line,
                "A SQL where clause appears to be built by joining strings with variable values.",
                "Use bind variables, for example psdi.mbo.SqlFormat with setObject, so values cannot change the query. This blocks SQL injection and quoting errors.",
            ))
    return findings


# --- LB004: Hardcoded environment values -------------------------------------

_SITE_ORG_SETVALUE = re.compile(r"setValue\s*\(\s*['\"](SITEID|ORGID)['\"]\s*,\s*['\"]", re.IGNORECASE)
_SITE_ORG_IN_SQL = re.compile(r"\b(siteid|orgid)\s*=\s*'[^']+'", re.IGNORECASE)
_URL = re.compile(r"^https?://", re.IGNORECASE)
_KNOWN_USERS = re.compile(r"^(MAXADMIN|MXINTADM|MAXINTADM|MAXREG|WILSON)$", re.IGNORECASE)


@rule("LB004", "Hardcoded site, organization, user or URL")
def hardcoded_values(script: Script) -> list[Finding]:
    findings = []
    for line in script.code_lines:
        reasons = []
        if _SITE_ORG_SETVALUE.search(line.code):
            reasons.append("a site or organization ID is set to a fixed value")
        for lit in _literals(line.code):
            if _SITE_ORG_IN_SQL.search(lit):
                reasons.append("a where clause filters on a fixed site or organization")
            if _URL.match(lit):
                reasons.append("a URL is written into the script")
            if _KNOWN_USERS.match(lit.strip()):
                reasons.append(f"a user name ({lit.strip()}) is written into the script")
        if reasons:
            findings.append(_finding(
                script, "LB004", "medium", line,
                "Hardcoded value: " + "; ".join(dict.fromkeys(reasons)) + ".",
                "Read environment-specific values from a system property or a domain so the script behaves the same in test and production.",
            ))
    return findings


# --- LB005: Access checks bypassed -------------------------------------------

# Matches the third (flags) argument only: setValue(attribute, value, flags).
_SETVALUE_FLAGS = re.compile(
    r"setValue\s*\(\s*[^,()]+,\s*(?:[^,()]|\([^()]*\))+,\s*"
    r"([\w.]*NO(?:ACCESSCHECK|VALIDATION|ACTION)\w*(?:\s*\|\s*[\w.]+)*|\d+L?)\s*\)"
)


# Commented-out code: starts like a call or assignment, or contains a method call.
_CODE_LIKE = re.compile(r"^[\w.]+\s*(?:\(|=[^=])|\w\.\w+\s*\(|[{}]\s*$")
_PLACEHOLDER = re.compile(r"^(todo|fixme|xxx|hack)\b", re.IGNORECASE)


def _explains(text: str) -> bool:
    """A comment that reads like an explanation: at least three words, not code, not a placeholder."""
    text = text.strip()
    if _PLACEHOLDER.match(text) or _CODE_LIKE.search(text):
        return False
    return len(re.findall(r"[A-Za-z]{2,}", text)) >= 3


def _documented(script: Script, line) -> bool:
    """True when the line, or a comment-only line directly above it, carries an explanation."""
    if line.comment and _explains(line.comment_text):
        return True
    # Read the whole comment block directly above (several # or // lines, or a /* */ block).
    texts = []
    idx = line.number - 2
    while idx >= 0:
        prev = script.lines[idx]
        if not prev.comment or prev.code.strip():
            break
        texts.insert(0, prev.comment_text)
        idx -= 1
    return bool(texts) and _explains(" ".join(t for t in texts if t))


_SETVALUE_RECEIVER = re.compile(r"(\w+)\s*\.\s*setValue\s*\(")
_LB005_GAP = 5  # lines; calls this close together on the same object are one block to review


@rule("LB005", "setValue bypasses access checks or validation")
def access_bypass(script: Script) -> list[Finding]:
    hits = []  # (line, flag, documented, receiver)
    for line in script.code_lines:
        m = _SETVALUE_FLAGS.search(line.code)
        if m:
            r = _SETVALUE_RECEIVER.search(line.code)
            hits.append((line, m.group(1), _documented(script, line), r.group(1) if r else ""))
    # Calls on the same object, close together and with the same documentation status,
    # become one finding: a block of thirty bypass calls is one decision to review, not thirty.
    groups: list[list] = []
    for hit in hits:
        prev = groups[-1][-1] if groups else None
        if (
            prev
            and hit[0].number - prev[0].number <= _LB005_GAP
            and hit[2] == prev[2]
            and hit[3] == prev[3]
        ):
            groups[-1].append(hit)
        else:
            groups.append([hit])
    findings = []
    for group in groups:
        first, documented, receiver = group[0][0], group[0][2], group[0][3]
        flags = list(dict.fromkeys(flag for _, flag, _, _ in group))
        flag_text = ("the flag " if len(flags) == 1 else "the flags ") + ", ".join(flags)
        if len(group) == 1:
            where = f"setValue is called with {flag_text}"
        else:
            lines = ", ".join(str(h[0].number) for h in group)
            on = f" on {receiver}" if receiver else ""
            where = f"{len(group)} setValue calls{on} (lines {lines}) use {flag_text}"
        if documented:
            findings.append(_finding(
                script, "LB005", "low", first,
                f"{where}, with a comment next to it.",
                "Read the comment and confirm the reason still holds. Bypass flags can skip security, validation or follow-on actions.",
            ))
        else:
            findings.append(_finding(
                script, "LB005", "medium", first,
                f"{where} and no comment explaining why. "
                + ("The flag can" if len(flags) == 1 else "These flags can")
                + " skip security, validation or follow-on actions.",
                "Remove the flag if it was added to make an error go away, which AI-generated code often does. If it is needed, add a comment that says why.",
            ))
    return findings


# --- LB006: Credentials in code ----------------------------------------------

_SECRET_ASSIGN = re.compile(
    r"\b\w*(password|passwd|pwd|apikey|api_key|secret|token)\w*\s*=\s*['\"][^'\"]{3,}['\"]", re.IGNORECASE
)
_SECRET_HEADER = re.compile(r"['\"](apikey|x-api-key|authorization|maxauth)['\"]\s*[:,]\s*['\"][^'\"]{6,}['\"]", re.IGNORECASE)


@rule("LB006", "Credential written into the script")
def hardcoded_credentials(script: Script) -> list[Finding]:
    findings = []
    for line in script.code_lines:
        if _SECRET_ASSIGN.search(line.code) or _SECRET_HEADER.search(line.code):
            findings.append(_finding(
                script, "LB006", "high", line,
                "A password, API key or token appears to be written into the script.",
                "Remove it, rotate the credential, and load it from a secure property or the integration framework's endpoint configuration.",
            ))
    return findings


# --- LB007: Sensitive data in logs -------------------------------------------

_LOG_CALL = re.compile(r"(service\.log\w*\s*\(|logger\.\w+\s*\(|\blog\.\w+\s*\(|^\s*print\b)")
_SENSITIVE = re.compile(r"(password|passwd|apikey|api_key|token|secret|maxauth)", re.IGNORECASE)


@rule("LB007", "Sensitive value written to a log")
def sensitive_logging(script: Script) -> list[Finding]:
    findings = []
    for line in script.code_lines:
        if _LOG_CALL.search(line.code) and _SENSITIVE.search(line.code):
            findings.append(_finding(
                script, "LB007", "high", line,
                "A log statement appears to include a password, key or token.",
                "Log that the value was present, never the value itself. Logs are often readable by more people than the data.",
            ))
    return findings


# --- LB008: No logging at all ------------------------------------------------

_ANY_LOG = re.compile(r"(service\.log|logger\.|\blog\.\w+\s*\(|\bprint\b|service\.error\s*\()")


@rule("LB008", "Script has no logging")
def no_logging(script: Script) -> list[Finding]:
    code = script.code_lines
    if not code or any(_ANY_LOG.search(line.code) for line in code):
        return []
    return [_finding(
        script, "LB008", "low", code[0],
        "The script writes nothing to the log.",
        "Add service.log_debug or service.log_info calls at key decisions so failures in production can be traced.",
    )]


# --- LB009: Explicit save ----------------------------------------------------

_SAVE = re.compile(r"(\w+)?\s*\.save\s*\(\s*\)")


def _server_set_names(script: Script) -> set[str]:
    servers = _server_names(script)
    names = set()
    for line in script.code_lines:
        for stmt in _statements(line.code):
            m = _SET_ASSIGN.match(stmt)
            if m and _is_server_call(m.group(2), servers):
                names.add(m.group(1))
    return names


@rule("LB009", "Explicit save() call")
def explicit_save(script: Script) -> list[Finding]:
    findings = []
    own_sets = _server_set_names(script)
    for line in script.code_lines:
        m = _SAVE.search(line.code)
        if m and m.group(1) in own_sets:
            continue  # saving a set the script opened through MXServer is the correct pattern
        if m:
            findings.append(_finding(
                script, "LB009", "low", line,
                "The script calls save() itself.",
                "In object and attribute launch points the framework saves the transaction. An extra save can trigger the script again or commit part of a change. Keep explicit saves for sets you opened through MXServer, and close them afterwards.",
            ))
    return findings


# --- LB010: Raw database connection never released ---------------------------

_DB_CONN_ASSIGN = re.compile(_DECL + r"(\w+)\s*=\s*.+\.(?:getDBConnection|getDBManager\s*\(\s*\)\s*\.\s*getConnection)\s*\(")
_DB_CONN_FREE = re.compile(r"\.(?:freeDBConnection|freeConnection)\s*\(")


@rule("LB010", "Database connection taken with getDBConnection is never released")
def unreleased_db_connection(script: Script) -> list[Finding]:
    findings = []
    # Match calls only outside string literals, so text that merely mentions the API is not flagged.
    def no_strings(code: str) -> str:
        return _STRING.sub('""', code)

    all_code = "\n".join(no_strings(line.code) for line in script.code_lines)
    if _DB_CONN_FREE.search(all_code):
        return findings
    for line in script.code_lines:
        m = next((m for m in map(_DB_CONN_ASSIGN.match, _statements(no_strings(line.code))) if m), None)
        if not m:
            continue
        findings.append(_finding(
            script, "LB010", "high", line,
            f"Database connection '{m.group(1)}' is taken from Maximo's connection pool but never given back.",
            "Release it in a finally block with freeDBConnection(connectionKey), or getDBManager().freeConnection(connectionKey) if you used getDBManager().getConnection, and close every Statement and ResultSet first. Closing the java.sql.Connection alone does not return it to Maximo's pool. "
            "Leaked connections drain Maximo's own connection pool. Prefer an MboSet with a SqlFormat where clause when you only need to read records.",
        ))
    return findings


# --- LB011 / LB012: Performance patterns from IBM's scripting best practices --------

_COUNT_CALL = re.compile(r"([\w.]+(?:\((?:[^()\"']|\"[^\"]*\"|'[^']*')*\))?)\s*\.\s*count\s*\(\s*\)")
_FUNC_HEADER = re.compile(r"^\s*def\s+\w+|\bfunction\b")
_REQUERY = re.compile(r"\.\s*(?:setWhere|setQbe|setUserWhere|reset|resetQbe)\s*\(")


def _in_string(code: str, pos: int) -> bool:
    return any(m.start() <= pos < m.end() for m in _STRING.finditer(code))


def _function_scope(script: Script, index: int) -> str:
    """The header of the nearest enclosing function, or "" at the top level."""
    return next((h for h in _enclosing_headers(script, index) if _FUNC_HEADER.search(h)), "")


@rule("LB011", "count() called more than once on the same set")
def repeated_count(script: Script) -> list[Finding]:
    tallies: dict[tuple[str, str], list] = {}
    flagged: dict[tuple[str, str], list] = {}
    for i, line in enumerate(script.lines):
        code = line.code
        if not code.strip():
            continue
        scope = _function_scope(script, i)
        # A set that is re-queried or reassigned needs a fresh count, so its tally restarts.
        for key in list(tallies):
            if key[0] != scope:
                continue
            root = re.escape(key[1].split(".")[0])
            if re.search(rf"\b{re.escape(key[1])}\s*{_REQUERY.pattern}", code) or re.search(
                rf"{_DECL}{root}\s*=[^=]", code
            ):
                if len(tallies[key]) >= 2:
                    flagged.setdefault(key, []).append(list(tallies[key]))
                del tallies[key]
        for m in _COUNT_CALL.finditer(code):
            if _in_string(code, m.start()):
                continue
            tallies.setdefault((scope, m.group(1)), []).append(line)
    for key, lines in tallies.items():
        if len(lines) >= 2:
            flagged.setdefault(key, []).append(lines)
    findings = []
    for (_, receiver), runs in flagged.items():
        for lines in runs:
            findings.append(_finding(
                script, "LB011", "low", lines[1],
                f"count() is called {len(lines)} times on {receiver}. Each call runs a separate SQL query.",
                "Call count() once, store the result in a variable and reuse it.",
            ))
    findings.sort(key=lambda f: f.line)
    return findings


_LOG_ARGS = re.compile(r"(?:service\.log\w*|logger\.\w+|\blog\.\w+)\s*\((.*)\)")
_COSTLY = re.compile(r"\.\s*count\s*\(|getMboSet\s*\(|getDBConnection\s*\(|executeQuery\s*\(")
_LOG_GUARD = re.compile(r"isLoggingEnabled|is(?:Debug|Info|Warn|Error|Trace)Enabled\s*\(|debugEnabled|loggingEnabled")


def _enclosing_headers(script: Script, index: int) -> list[str]:
    """Code of the block headers that enclose script.lines[index] (if, for, def and so on)."""
    lines = script.lines
    target = lines[index]
    headers = []
    if script.language == "javascript":
        depth = 0
        for line in reversed(lines[:index]):
            code = _STRING.sub('""', line.code)
            for ch in reversed(code):
                if ch == "}":
                    depth += 1
                elif ch == "{":
                    depth -= 1
            if depth < 0:
                headers.append(code)
                depth = 0
        return headers
    indent = target.indent
    for line in reversed(lines[:index]):
        if line.code.strip() and line.indent < indent:
            headers.append(line.code)
            indent = line.indent
    return headers


_GUARD_ASSIGN = re.compile(_DECL + r"(\w+)\s*=\s*.*(?:isLoggingEnabled|is(?:Debug|Info|Warn|Error|Trace)Enabled)\s*\(")


@rule("LB012", "Costly call inside a log statement without a logging check")
def costly_logging(script: Script) -> list[Finding]:
    findings = []
    # Variables that hold the result of a logging check count as guards too.
    names = {m.group(1) for line in script.code_lines for m in [_GUARD_ASSIGN.match(line.code)] if m}
    guard_names = re.compile("|".join(rf"(?<![.\w]){re.escape(n)}\b" for n in names)) if names else None

    def guarded(code: str) -> bool:
        return bool(_LOG_GUARD.search(code) or (guard_names and guard_names.search(code)))

    for i, line in enumerate(script.lines):
        if not line.code.strip():
            continue
        m = _LOG_ARGS.search(line.code)
        if not m or not _COSTLY.search(_STRING.sub('""', m.group(1))):
            continue
        if guarded(line.code) or any(guarded(h) for h in _enclosing_headers(script, i)):
            continue
        findings.append(_finding(
            script, "LB012", "low", line,
            "A log statement runs a query (such as count() or getMboSet) even when logging is turned off. Log arguments are evaluated first.",
            "Wrap it in if service.isLoggingEnabled(): (Maximo 7.6.1.2 and later) or a logger.isDebugEnabled() check, or log a value you already have.",
        ))
    return findings


def run_all(script: Script, enabled: set[str] | None = None) -> list[Finding]:
    findings: list[Finding] = []
    for rule_id, _title, fn in RULES:
        if enabled is not None and rule_id not in enabled:
            continue
        findings.extend(fn(script))
    findings.sort(key=lambda f: (f.line, -SEVERITY_ORDER[f.severity], f.rule_id))
    return findings

# ---- rule_help.py ----
"""Longer help text for each rule, used in SARIF output so code scanning tools can explain a finding.

Each entry: default severity, category tag, optional security-severity (GitHub scale 0.1 to 10,
only for security rules), and help text that says why it matters and how to fix it.
"""


RULE_HELP: dict[str, dict] = {
    "LB001": {
        "severity": "high",
        "tag": "reliability",
        "help": (
            "A set opened with MXServer.getMXServer().getMboSet() sits outside the current transaction, "
            "so the script that opens it must close it. An unclosed set keeps holding database resources, "
            "which adds up in scripts that run often. Fix: call close() (or cleanup()) on the set in a "
            "finally block, or use a relationship from the current record when one exists."
        ),
    },
    "LB002": {
        "severity": "medium",
        "tag": "performance",
        "help": (
            "Opening a new MboSet on every pass of a loop runs a separate query and creates a separate "
            "resource to close each time. Fix: open the set once before the loop and change its where "
            "clause inside it, or use a relationship from the current record."
        ),
    },
    "LB003": {
        "severity": "high",
        "tag": "security",
        "security_severity": "7.5",
        "help": (
            "A where clause built by joining strings with values breaks on values that contain quotes, "
            "and lets a value taken from a user or an integration change the query (SQL injection). "
            "Fix: write the clause with :1, :2 placeholders using psdi.mbo.SqlFormat and pass each value "
            "with setObject."
        ),
    },
    "LB004": {
        "severity": "medium",
        "tag": "maintainability",
        "help": (
            "A site, organization, user name or URL typed into the script works only in the environment "
            "it was written for and can do the wrong thing after a move to test, production or a new MAS "
            "instance. Fix: read environment-specific values from a system property or a domain, or from "
            "the record the script runs on."
        ),
    },
    "LB005": {
        "severity": "medium",
        "tag": "security",
        "security_severity": "5.0",
        "help": (
            "setValue flags such as NOACCESSCHECK, NOVALIDATION or NOACTION skip access checks, field "
            "validation or follow-on actions. They are sometimes added only to make an error go away. "
            "Fix: remove the flag if it is not needed. If it is needed, add a comment on the same line or "
            "directly above that explains why, so reviewers can confirm the reason still holds. Findings "
            "with an explaining comment are reported at low severity."
        ),
    },
    "LB006": {
        "severity": "high",
        "tag": "security",
        "security_severity": "7.5",
        "help": (
            "Script source is stored in the Maximo database and shown in the Automation Scripts "
            "application, so a password, API key or token written into it can be read by anyone with "
            "that access. Fix: remove it, rotate the credential, and load it from a secure property or "
            "the integration framework's endpoint configuration."
        ),
    },
    "LB007": {
        "severity": "high",
        "tag": "security",
        "security_severity": "7.0",
        "help": (
            "Logs are often readable by more people than the data they describe. Writing a password, "
            "token or other sensitive value to a log exposes it. Fix: log that the value was present, "
            "never the value itself."
        ),
    },
    "LB008": {
        "severity": "low",
        "tag": "maintainability",
        "help": (
            "A script that writes nothing to the log is hard to trace when it fails in production. "
            "Fix: add service.log_debug or service.log_info calls at key decisions."
        ),
    },
    "LB009": {
        "severity": "low",
        "tag": "reliability",
        "help": (
            "In object and attribute launch points the framework saves the transaction. An extra save() "
            "can run the script again or commit part of a change. Fix: keep explicit saves for sets you "
            "opened yourself through MXServer."
        ),
    },
    "LB010": {
        "severity": "high",
        "tag": "reliability",
        "help": (
            "A connection taken with getDBConnection comes from Maximo's own connection pool. If it is "
            "not given back, it drains that pool. Closing the java.sql.Connection alone does not return "
            "it. Fix: in a finally block, close every Statement and ResultSet, then return the connection "
            "with freeDBConnection(connectionKey), or getDBManager().freeConnection(connectionKey) if you "
            "used getDBManager().getConnection. Prefer an "
            "MboSet with a SqlFormat where clause when you only need to read records."
        ),
    },
    "LB011": {
        "severity": "low",
        "tag": "performance",
        "help": (
            "Each call to count() runs a SQL count query. Calling it twice on the same set doubles the "
            "work. Fix: call count() once, store the result in a variable and reuse it."
        ),
    },
    "LB012": {
        "severity": "low",
        "tag": "performance",
        "help": (
            "Arguments to a log call are evaluated before the logger decides whether to write anything, "
            "so a query inside a log statement runs even when logging is off. Fix: wrap it in a "
            "logging-enabled check such as service.isLoggingEnabled() (Maximo 7.6.1.2 and later) or "
            "logger.isDebugEnabled(), or log a value you already have."
        ),
    },
}

# ---- cli.py ----
"""Command-line entry point: lbcheck."""


import argparse
import json
import sys
from pathlib import Path
from urllib.parse import quote


SCRIPT_SUFFIXES = {".py", ".jy", ".jython", ".js"}


def collect_files(paths: list[str]) -> list[Path]:
    files: list[Path] = []
    for p in map(Path, paths):
        if p.is_dir():
            files.extend(sorted(f for f in p.rglob("*") if f.is_file() and f.suffix.lower() in SCRIPT_SUFFIXES))
        elif p.is_file():
            files.append(p)
        else:
            print(f"lbcheck: not found: {p}", file=sys.stderr)
    return files


def format_text(findings: list[Finding], file_count: int) -> str:
    out: list[str] = []
    current = None
    for f in findings:
        if f.path != current:
            current = f.path
            out.append(f"\n{f.path}")
        out.append(f"  line {f.line}: [{f.severity.upper()}] {f.rule_id} {f.message}")
        if f.snippet:
            out.append(f"      > {f.snippet}")
        out.append(f"      fix: {f.suggestion}")
    counts = {s: sum(1 for f in findings if f.severity == s) for s in ("high", "medium", "low")}
    out.append(
        f"\nChecked {file_count} file(s): {counts['high']} high, {counts['medium']} medium, {counts['low']} low."
    )
    out.append("Findings flag patterns to review. They are not proof of a defect.")
    return "\n".join(out).lstrip("\n")


SARIF_LEVELS = {"high": "error", "medium": "warning", "low": "note"}


def sarif_location(path: str, base: Path | None = None) -> dict:
    """Artifact location relative to the working folder when possible, so code scanning can attach it to a file."""
    p = Path(path)
    base = (base or Path.cwd()).resolve()
    try:
        rel = p.resolve().relative_to(base)
    except ValueError:
        return {"uri": p.resolve().as_uri()}
    return {"uri": quote(rel.as_posix()), "uriBaseId": "%SRCROOT%"}


def sarif_rule(rule_id: str, title: str) -> dict:
    """Rule metadata for SARIF: title, help text, default level and tags for code scanning."""
    entry: dict = {"id": rule_id, "name": rule_id, "shortDescription": {"text": title}}
    info = RULE_HELP.get(rule_id)
    if info:
        entry["fullDescription"] = {"text": info["help"]}
        entry["help"] = {"text": info["help"]}
        entry["defaultConfiguration"] = {"level": SARIF_LEVELS[info["severity"]]}
        props: dict = {"tags": [info["tag"], "maximo"]}
        if "security_severity" in info:
            props["security-severity"] = info["security_severity"]
        entry["properties"] = props
    return entry


def format_sarif(findings: list[Finding]) -> dict:
    """SARIF 2.1.0 log, readable by GitHub code scanning and most editors."""
    rules = [sarif_rule(rule_id, title) for rule_id, title, _ in RULES]
    results = []
    for f in findings:
        results.append(
            {
                "ruleId": f.rule_id,
                "level": SARIF_LEVELS.get(f.severity, "warning"),
                "message": {"text": f"{f.message} Fix: {f.suggestion}"},
                "locations": [
                    {
                        "physicalLocation": {
                            "artifactLocation": sarif_location(f.path),
                            "region": {"startLine": max(f.line, 1)},
                        }
                    }
                ],
            }
        )
    return {
        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
        "version": "2.1.0",
        "runs": [
            {
                "tool": {
                    "driver": {
                        "name": "lbcheck",
                        "version": __version__,
                        "informationUri": "https://loadbearingeam.com",
                        "rules": rules,
                    }
                },
                "results": results,
            }
        ],
    }


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="lbcheck",
        description="Check IBM Maximo automation scripts for risky patterns before go-live.",
    )
    parser.add_argument("paths", nargs="*", help="Script files or folders to check.")
    parser.add_argument("--format", choices=["text", "json", "sarif"], default="text")
    parser.add_argument(
        "--fail-on",
        choices=["low", "medium", "high", "never"],
        default="high",
        help="Exit with code 1 when a finding at or above this severity exists (default: high).",
    )
    parser.add_argument("--rules", help="Comma-separated rule IDs to run, for example LB001,LB003.")
    parser.add_argument("--list-rules", action="store_true", help="List the rules and exit.")
    parser.add_argument("--version", action="version", version=f"lbcheck {__version__}")
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    if args.list_rules:
        for rule_id, title, _ in RULES:
            print(f"{rule_id}  {title}")
        return 0
    if not args.paths:
        build_parser().print_usage(sys.stderr)
        return 2
    enabled = {r.strip().upper() for r in args.rules.split(",")} if args.rules else None
    files = collect_files(args.paths)
    findings: list[Finding] = []
    for f in files:
        findings.extend(run_all(load(f), enabled))
    if args.format == "json":
        print(json.dumps({"version": __version__, "files": len(files), "findings": [f.to_dict() for f in findings]}, indent=2))
    elif args.format == "sarif":
        print(json.dumps(format_sarif(findings), indent=2))
    else:
        print(format_text(findings, len(files)))
    if args.fail_on == "never":
        return 0
    threshold = SEVERITY_ORDER[args.fail_on]
    return 1 if any(SEVERITY_ORDER[f.severity] >= threshold for f in findings) else 0


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