#!/usr/bin/env python3
# =====================================================================
# J-Code 0.3.0 — the drop-in single file (SPEC §9.1).
#
# GENERATED FILE — do not edit. Built by scripts/build_single.py from
# the jcode package sources (src/jcode/), which are embedded verbatim
# below; the package and this file can never drift.
#
# Drop this file into any project root and run:
#     python3 jcode.py audit .
#     python3 jcode.py fix .          # dry-run plan (modifies nothing)
#     python3 jcode.py fix . --yes    # apply the safe fixes, with backups
#
# J-Code finds — and safely fixes — the errors hiding in vibe-coded
# projects. Created by Hein Htet Aung. Python 3.9+ stdlib only.
# =====================================================================

_MODULE_SOURCES = {
    'jcode': r'''"""J-Code — finds and fixes errors in vibe-coded projects.

Created by Hein Htet Aung. Implementation lands after the test suite
(spec first, tests first — the J-Code method, RULES §17).
"""
__version__ = "0.3.0"
''',
    'jcode.scan': r'''"""File discovery and text scanning (stdlib only).

The comment/string handling is a small hand-written lexer, not naive regex:
real-world JS defeats flat scanners with template literals containing
${ ... } expressions (which may nest more templates), and with regex
literals containing quotes or // sequences. Both are handled here:
template ${} nesting is tracked on a stack, and a / is treated as a regex
start only when the previous significant token cannot end a value
(the standard heuristic). PHP mode disables JS templates/regexes and
adds # comments and heredocs.
"""
import bisect
import fnmatch
import os
import re

SKIP_DIRS = {".git", "node_modules", "vendor", "__pycache__",
             # J-Code's own fix backups (SPEC §9.1): byte copies of project
             # files — scanning them would invent duplicate definitions,
             # and they must not count as (D) basename candidates.
             ".jcode-backup"}
MAX_FILE_BYTES = 5 * 1024 * 1024
CODE_EXTS = {".js", ".html", ".htm", ".php", ".py"}


def is_minified(filename):
    """Minified/generated bundle (pdf.min.js, hls.min.js, …): its
    internals are machine-generated, not hand-written code (SPEC §7.3)."""
    return ".min." in filename.lower()


def path_excluded(rel, patterns):
    """SPEC §7.3 pattern semantics (the simple version): patterns match
    the project-relative path with forward slashes. No '/' -> any single
    path component via fnmatch; with '/' -> the whole relative path via
    fnmatch; trailing '/' -> that directory (by name anywhere, or as a
    path prefix when the pattern itself contains '/')."""
    r = rel.replace(os.sep, "/")
    parts = r.split("/")
    for pat in patterns:
        p = (pat or "").strip()
        if not p or p.startswith("#"):
            continue
        if p.endswith("/"):
            q = p.rstrip("/")
            if "/" in q:
                if r == q or r.startswith(q + "/"):
                    return True
            elif q in parts:
                return True
        elif "/" in p:
            if fnmatch.fnmatch(r, p):
                return True
        else:
            if any(fnmatch.fnmatch(c, p) for c in parts):
                return True
    return False

_REGEX_PRECEDING_KEYWORDS = {
    "return", "typeof", "case", "in", "of", "new", "delete", "void",
    "instanceof", "do", "else", "yield", "await", "throw",
}
_HEREDOC_START = re.compile(r"<<<[ \t]*['\"]?([A-Za-z_]\w*)['\"]?")


def iter_project_files(root, excludes=(), skip_minified=False, stats=None,
                       exclude_files=()):
    """(relpath, abspath) for every code file under root, sorted.

    excludes: SPEC §7.3 patterns (from .jcodeignore / --exclude);
    skip_minified: drop *.min.* bundles. When a dict is passed as
    `stats`, it gains skipped_excluded / skipped_minified counts.
    exclude_files: absolute paths skipped silently (SPEC §9.1 — the
    running tool never scans its own file). Defaults reproduce v0.1
    behaviour exactly."""
    skip_abs = {os.path.abspath(p) for p in exclude_files}
    out = []
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS)
        if excludes:
            dirnames[:] = [
                d for d in dirnames
                if not path_excluded(
                    os.path.relpath(os.path.join(dirpath, d), root),
                    excludes)]
        for fn in sorted(filenames):
            if os.path.splitext(fn)[1].lower() not in CODE_EXTS:
                continue
            ap = os.path.join(dirpath, fn)
            if os.path.abspath(ap) in skip_abs:
                continue
            rel = os.path.relpath(ap, root)
            if excludes and path_excluded(rel, excludes):
                if stats is not None:
                    stats["skipped_excluded"] = \
                        stats.get("skipped_excluded", 0) + 1
                continue
            if skip_minified and is_minified(fn):
                if stats is not None:
                    stats["skipped_minified"] = \
                        stats.get("skipped_minified", 0) + 1
                continue
            out.append((rel, ap))
    return out


def all_project_files(root):
    """Relpaths of ALL files (any type) — for existence / basename lookups."""
    out = []
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
        for fn in filenames:
            out.append(os.path.relpath(os.path.join(dirpath, fn), root))
    return out


def read_text(path):
    with open(path, "r", encoding="utf-8", errors="replace") as fh:
        return fh.read()


def _lex_transform(text, lang, blank):
    """Walk text with the lexer; comments -> spaces always, and when
    blank=True also string/template/regex literal contents -> spaces.
    Offsets and line numbers are preserved exactly."""
    js = (lang == "js")
    out = []
    i, n = 0, len(text)
    mode = "code"          # code|sq|dq|tpl|regex|line|block|heredoc
    tpl_stack = []         # brace depths of open ${ } expressions
    regex_class = False
    heredoc_end = None
    prev_value = False     # previous significant code token was value-like
    prev_word = ""
    cur_word = ""

    def emit(ch, kind):
        if kind == "comment" or (blank and kind == "string"):
            out.append("\n" if ch == "\n" else " ")
        else:
            out.append(ch)

    def flush_word():
        nonlocal cur_word, prev_word, prev_value
        if cur_word:
            prev_word = cur_word
            cur_word = ""
            prev_value = prev_word not in _REGEX_PRECEDING_KEYWORDS

    while i < n:
        ch = text[i]
        nxt = text[i + 1] if i + 1 < n else ""

        if mode == "line":
            emit(ch, "comment")
            if ch == "\n":
                mode = "code"
            i += 1
            continue
        if mode == "block":
            if ch == "*" and nxt == "/":
                emit(ch, "comment")
                emit(nxt, "comment")
                i += 2
                mode = "code"
                continue
            emit(ch, "comment")
            i += 1
            continue
        if mode in ("sq", "dq"):
            quote = "'" if mode == "sq" else '"'
            if ch == "\\" and i + 1 < n:
                emit(ch, "string")
                emit(text[i + 1], "string")
                i += 2
                continue
            emit(ch, "string" if ch != quote else "code")
            # JS strings cannot span lines (bail out defensively); PHP
            # single/double-quoted strings CAN, so in PHP mode only the
            # closing quote ends the string.
            if ch == quote or (js and ch == "\n"):
                mode = "code"
                prev_value = True
                prev_word = ""
            i += 1
            continue
        if mode == "tpl":
            if ch == "\\" and i + 1 < n:
                emit(ch, "string")
                emit(text[i + 1], "string")
                i += 2
                continue
            if ch == "`":
                emit(ch, "code")
                mode = "code"
                prev_value = True
                prev_word = ""
                i += 1
                continue
            if ch == "$" and nxt == "{":
                emit(ch, "code")
                emit(nxt, "code")
                tpl_stack.append(0)
                mode = "code"
                prev_value = False
                i += 2
                continue
            emit(ch, "string")
            i += 1
            continue
        if mode == "regex":
            if ch == "\\" and i + 1 < n:
                emit(ch, "string")
                emit(text[i + 1], "string")
                i += 2
                continue
            if ch == "[":
                regex_class = True
            elif ch == "]":
                regex_class = False
            elif ch == "/" and not regex_class:
                emit(ch, "code")
                mode = "code"
                prev_value = True
                prev_word = ""
                i += 1
                continue
            elif ch == "\n":
                mode = "code"  # unterminated regex: bail out defensively
                emit(ch, "code")
                i += 1
                continue
            emit(ch, "string")
            i += 1
            continue
        if mode == "heredoc":
            # at a line start, the terminator word ends the heredoc
            if (i == 0 or text[i - 1] == "\n") and text.startswith(
                    heredoc_end, i):
                after = i + len(heredoc_end)
                if after >= n or text[after] in ";\n\r":
                    for c in heredoc_end:
                        emit(c, "code")
                    i = after
                    mode = "code"
                    prev_value = True
                    continue
            emit(ch, "string")
            i += 1
            continue

        # ---- code mode ----
        if not js and ch == "#":
            mode = "line"
            emit(ch, "comment")
            i += 1
            continue
        if ch == "/" and nxt == "/":
            flush_word()
            mode = "line"
            emit(ch, "comment")
            emit(nxt, "comment")
            i += 2
            continue
        if ch == "/" and nxt == "*":
            flush_word()
            mode = "block"
            emit(ch, "comment")
            emit(nxt, "comment")
            i += 2
            continue
        if not js and text.startswith("<<<", i):
            m = _HEREDOC_START.match(text, i)
            if m:
                flush_word()
                for c in m.group(0):
                    emit(c, "code")
                i = m.end()
                heredoc_end = m.group(1)
                mode = "heredoc"
                continue
        if ch == "'":
            flush_word()
            mode = "sq"
            emit(ch, "code")
            i += 1
            continue
        if ch == '"':
            flush_word()
            mode = "dq"
            emit(ch, "code")
            i += 1
            continue
        if js and ch == "`":
            flush_word()
            mode = "tpl"
            emit(ch, "code")
            i += 1
            continue
        if js and ch == "/":
            flush_word()
            if not prev_value or prev_word in _REGEX_PRECEDING_KEYWORDS:
                mode = "regex"
                regex_class = False
                emit(ch, "code")
                i += 1
                continue
            emit(ch, "code")  # division operator
            prev_value = False
            prev_word = ""
            i += 1
            continue
        if js and tpl_stack and ch == "{":
            tpl_stack[-1] += 1
            emit(ch, "code")
            prev_value = False
            i += 1
            continue
        if js and tpl_stack and ch == "}":
            if tpl_stack[-1] == 0:
                tpl_stack.pop()
                mode = "tpl"
                emit(ch, "code")
                i += 1
                continue
            tpl_stack[-1] -= 1
            emit(ch, "code")
            prev_value = True
            i += 1
            continue
        # ordinary code character: maintain prev-token tracking (JS only)
        if js:
            if ch.isalnum() or ch in "_$":
                cur_word += ch
            elif ch in " \t\r\n":
                if cur_word:
                    flush_word()
            else:
                flush_word()
                prev_value = ch in ")] }"
                if ch not in " \t\r\n":
                    prev_word = ""
        emit(ch, "code")
        i += 1

    return "".join(out)


def strip_comments(text, lang="js"):
    """Remove //, /* */ (and #, heredoc-aware, for lang='php') comments.
    String literals are preserved verbatim; line layout is preserved."""
    return _lex_transform(text, lang, blank=False)


def blank_strings(text, lang="js"):
    """Blank string/template/regex literal contents (delimiters kept).
    Run AFTER strip_comments with the same lang. ${ } expressions inside
    templates are real code and are preserved."""
    return _lex_transform(text, lang, blank=True)


def line_starts(text):
    starts = [0]
    for i, ch in enumerate(text):
        if ch == "\n":
            starts.append(i + 1)
    return starts


def line_at(starts, offset):
    """1-based line number for a character offset."""
    return bisect.bisect_right(starts, offset)


def prev_word(code, offset):
    """The identifier-ish word immediately before offset (skipping spaces)."""
    i = offset - 1
    while i >= 0 and code[i] in " \t\r\n":
        i -= 1
    j = i
    while j >= 0 and (code[j].isalnum() or code[j] in "_$"):
        j -= 1
    return code[j + 1:i + 1]
''',
    'jcode.js': r'''"""JavaScript analysis: definitions, calls, and client->server URLs.

Works on comment-stripped, string-blanked code for defs/calls, and on
comment-stripped (strings intact) code for URL extraction.
"""
import re

IDENT = r"[A-Za-z_$][\w$]*"

JS_KEYWORDS = set("""
if else for while do switch case default catch try finally return typeof
instanceof in of new delete void throw function var let const class extends
super this yield await async break continue debugger export import from with
label static get set
""".split())

# Globals a browser/ES environment (or a ubiquitous library) provides.
JS_BUILTINS = set("""
parseInt parseFloat isNaN isFinite decodeURI decodeURIComponent encodeURI
encodeURIComponent escape unescape Number String Boolean BigInt Symbol Array
Object Function Proxy Reflect Error EvalError RangeError ReferenceError
SyntaxError TypeError URIError AggregateError Date RegExp Map Set WeakMap
WeakSet Promise Intl ArrayBuffer SharedArrayBuffer DataView Atomics fetch
Headers Request Response URL URLSearchParams TextEncoder TextDecoder Blob
File FileReader FormData Event CustomEvent EventTarget Image Audio Option
Worker SharedWorker AbortController AbortSignal setTimeout setInterval
clearTimeout clearInterval setImmediate clearImmediate queueMicrotask
requestAnimationFrame cancelAnimationFrame requestIdleCallback
cancelIdleCallback alert confirm prompt open close focus blur print
postMessage scroll scrollTo scrollBy getComputedStyle matchMedia getSelection
find stop addEventListener removeEventListener dispatchEvent btoa atob
structuredClone WebSocket XMLHttpRequest MutationObserver IntersectionObserver
ResizeObserver PerformanceObserver DOMParser XMLSerializer Notification
AudioContext webkitAudioContext OfflineAudioContext RTCPeerConnection
MediaRecorder $ jQuery require define moment _ Vue React ReactDOM angular
echarts Hls Chart Plyr Swiper toastr Swal firebase google createImageBitmap
importScripts reportError OffscreenCanvas ImageBitmap ImageData Path2D
""".split())

_DEF_PATTERNS = [
    re.compile(r"\bfunction\s*\*?\s*(" + IDENT + r")\s*\("),
    re.compile(r"\b(?:var|let|const)\s+(" + IDENT + r")\s*="),
    re.compile(r"(?<![\w$.])(" + IDENT + r")\s*=\s*(?:async\s+)?"
               r"(?:function\b|\([^()]*\)\s*=>|" + IDENT + r"\s*=>)"),
    re.compile(r"\b(?:window|globalThis|self|this)\.(" + IDENT + r")\s*="),
    re.compile(r"\b(?:get|set)\s+(" + IDENT + r")\s*\("),
    re.compile(r"(" + IDENT + r")\s*:\s*(?:async\s+)?"
               r"(?:function\b|\([^()]*\)\s*=>)"),
    re.compile(r"(?m)^\s*(?:async\s+)?(" + IDENT + r")\s*\([^()]*\)\s*\{"),
    re.compile(r"[{,]\s*(?:async\s+)?(" + IDENT + r")\s*\([^()]*\)\s*\{"),
]

CALL_RE = re.compile(r"(?<![\w$.])(" + IDENT + r")\s*\(")

_FUNC_PARAMS_RE = re.compile(r"\bfunction\s*\*?\s*(?:" + IDENT + r")?\s*\(([^()]*)\)")
_ARROW_PARAMS_RE = re.compile(r"\(([^()]*)\)\s*=>")
_ARROW_ONE_RE = re.compile(r"(?<![\w$.])(" + IDENT + r")\s*=>")
_PARAM_NAME_RE = re.compile(IDENT)


def extract_definitions(code):
    """name -> [offsets] for every definition site in string-blanked code."""
    defs = {}
    for pat in _DEF_PATTERNS:
        for m in pat.finditer(code):
            name = m.group(1)
            if name in JS_KEYWORDS:
                continue
            defs.setdefault(name, []).append(m.start(1))
    return defs


def _param_names(chunk):
    out = set()
    for part in chunk.split(","):
        part = part.strip().lstrip(".")
        m = _PARAM_NAME_RE.match(part)
        if m:
            out.add(m.group(0))
    return out


def extract_params(code):
    """All parameter names used anywhere in this unit.

    v0.1 over-approximation: parameters are treated as known names for the
    whole unit, which avoids false 'undefined' reports for callbacks.
    """
    names = set()
    for m in _FUNC_PARAMS_RE.finditer(code):
        names.update(_param_names(m.group(1)))
    for m in _ARROW_PARAMS_RE.finditer(code):
        names.update(_param_names(m.group(1)))
    for m in _ARROW_ONE_RE.finditer(code):
        names.add(m.group(1))
    return names


def extract_calls(code):
    """Yield (name, offset) for every bare call candidate."""
    for m in CALL_RE.finditer(code):
        yield m.group(1), m.start(1)


# ---- client -> server URL extraction (strings intact) ----

_Q = r"(['\"`])((?:(?!\1).)*)\1"
_URL_PATTERNS = [
    re.compile(r"\bfetch\s*\(\s*" + _Q, re.S),
    re.compile(r"\.open\s*\(\s*['\"][A-Z]+['\"]\s*,\s*" + _Q, re.S),
    re.compile(r"\$\s*\.\s*(?:get|post|getJSON)\s*\(\s*" + _Q, re.S),
    re.compile(r"\$\s*\.\s*ajax\s*\(\s*\{[^}]*?\burl\s*:\s*" + _Q, re.S),
    re.compile(r"\baxios\s*\.\s*(?:get|post|put|delete|patch)\s*\(\s*" + _Q, re.S),
]


def extract_client_urls(code):
    """Yield (url, offset, is_dynamic) for literal client request URLs.

    A URL counts as dynamic when it is a template literal containing ${...}
    or when the literal is concatenated with something ('...' + x).
    """
    seen = []
    for pat in _URL_PATTERNS:
        for m in pat.finditer(code):
            url = m.group(2)
            quote = m.group(1)
            dynamic = False
            if quote == "`" and "${" in url:
                dynamic = True
            tail = code[m.end():m.end() + 8].lstrip()
            if tail.startswith("+"):
                dynamic = True
            seen.append((url, m.start(2), dynamic))
    return seen
''',
    'jcode.php': r'''"""PHP analysis: definitions, calls, includes.

PHP function names are case-insensitive, so all comparisons are lowercased.
Calls are extracted from comment-stripped, string-blanked code; include
targets from comment-stripped code with strings intact.
"""
import re

# Language constructs that look like calls but are not functions.
PHP_CONSTRUCTS = set("""
echo print isset empty unset include include_once require require_once exit
die eval list array throw catch if elseif while for foreach switch declare
match fn clone new function class return global static instanceof endwhile
endfor endforeach endswitch endif and or xor use
""".split())

# PHP standard-library functions a normal web app uses (allowlist for (E)).
PHP_BUILTINS = set("""
strlen mb_strlen strpos mb_strpos stripos mb_stripos strrpos strripos substr
mb_substr substr_count substr_replace str_replace str_ireplace str_repeat
str_pad str_split str_word_count trim ltrim rtrim strtolower strtoupper
mb_strtolower mb_strtoupper ucfirst lcfirst ucwords strrev strcmp strcasecmp
strncmp strncasecmp strnatcmp strnatcasecmp strstr stristr strchr strrchr
strtok sprintf printf vsprintf vprintf fprintf number_format nl2br wordwrap
chunk_split explode implode join str_getcsv parse_str parse_url urlencode
urldecode rawurlencode rawurldecode base64_encode base64_decode bin2hex
hex2bin chr ord mb_chr mb_ord crc32 md5 sha1 hash hash_hmac hash_equals
hash_algos hash_file md5_file sha1_file hash_pbkdf2 password_hash
password_verify password_needs_rehash password_get_info
quoted_printable_encode quoted_printable_decode convert_uuencode
convert_uudecode metaphone soundex similar_text levenshtein preg_match
preg_match_all preg_replace preg_replace_callback preg_split preg_quote
preg_grep preg_last_error preg_filter mb_ereg_replace mb_split
mb_convert_encoding mb_detect_encoding mb_check_encoding mb_internal_encoding
mb_language mb_send_mail mb_substr_count mb_strimwidth mb_strwidth iconv
htmlentities htmlspecialchars html_entity_decode htmlspecialchars_decode
strip_tags addslashes stripslashes addcslashes stripcslashes quotemeta
get_html_translation_table preg_replace_callback_array str_contains
str_starts_with str_ends_with array_push array_pop array_shift array_unshift
array_map array_filter array_reduce array_merge array_merge_recursive
array_combine array_keys array_values array_key_exists array_key_first
array_key_last array_search in_array array_unique array_flip array_reverse
array_slice array_splice array_sum array_product array_chunk array_column
array_fill array_fill_keys range count sizeof array_diff array_diff_assoc
array_diff_key array_diff_uassoc array_intersect array_intersect_assoc
array_intersect_key array_multisort sort rsort asort arsort ksort krsort
usort uasort uksort natsort natcasesort shuffle array_rand array_walk
array_walk_recursive array_count_values array_pad array_replace
array_replace_recursive compact extract current next prev reset end key pos
is_array abs ceil floor round sqrt pow exp log log10 log2 sin cos tan asin
acos atan atan2 sinh cosh tanh pi max min rand mt_rand random_int
random_bytes srand mt_srand getrandmax mt_getrandmax lcg_value fmod intval
floatval doubleval boolval strval is_numeric is_int is_float is_integer
is_double is_long is_real is_nan is_infinite is_finite bindec decbin dechex
decoct hexdec octdec base_convert deg2rad rad2deg hypot intdiv date time
mktime strtotime gmdate gmmktime strftime gmstrftime date_create date_format
date_parse checkdate getdate localtime idate microtime hrtime
date_default_timezone_set date_default_timezone_get date_diff date_add
date_sub date_modify date_timestamp_get date_timestamp_set date_time_set
date_date_set date_isodate_set date_timezone_set date_offset_get
date_create_from_format date_get_last_errors file_exists is_file is_dir
is_readable is_writable is_writeable is_executable file_get_contents
file_put_contents file fopen fclose fread fwrite fputs fgets fgetc fgetss
fseek ftell rewind feof fflush ftruncate flock fputcsv fgetcsv basename
dirname realpath pathinfo filesize filetype filemtime fileatime filectime
fileperms fileowner filegroup unlink copy rename mkdir rmdir scandir glob
opendir readdir rewinddir closedir chdir getcwd chroot chmod chown chgrp
touch tempnam tmpfile sys_get_temp_dir readfile readlink link symlink stat
lstat disk_free_space disk_total_space diskfreespace move_uploaded_file
is_uploaded_file parse_ini_file parse_ini_string clearstatcache fpassthru
rewinddir stream_copy_to_stream stream_get_contents stream_context_create
json_encode json_decode json_last_error json_last_error_msg json_validate
serialize unserialize var_export print_r var_dump is_null is_bool is_string
is_object is_scalar is_callable is_iterable gettype settype define defined
constant function_exists class_exists method_exists property_exists
interface_exists trait_exists enum_exists get_class get_parent_class
get_called_class is_subclass_of is_a spl_autoload_register spl_object_id
spl_object_hash class_alias get_defined_vars get_defined_functions
get_defined_constants get_include_path set_include_path extension_loaded
get_loaded_extensions phpversion phpinfo php_uname getenv putenv setlocale
set_time_limit ignore_user_abort connection_aborted connection_status
register_shutdown_function error_reporting error_log trigger_error
set_error_handler restore_error_handler set_exception_handler
restore_exception_handler header headers_sent headers_list http_response_code
session_start session_destroy session_id session_name session_status
session_regenerate_id session_write_close session_unset session_get_cookie_params
session_set_cookie_params setcookie setrawcookie mail filter_var filter_input
filter_input_array filter_var_array filter_has_var filter_id filter_list
mysqli_connect mysqli_connect_error mysqli_connect_errno
mysqli_real_escape_string mysqli_close mysqli_set_charset mysqli_insert_id
mysqli_affected_rows mysqli_num_rows mysqli_fetch_assoc mysqli_fetch_array
mysqli_fetch_object mysqli_fetch_row mysqli_prepare mysqli_stmt_bind_param
mysqli_stmt_execute mysqli_stmt_get_result mysqli_stmt_close mysqli_error
mysqli_errno mysqli_begin_transaction mysqli_commit mysqli_rollback
mysqli_query mysqli_autocommit mysqli_select_db mysqli_ping mysqli_thread_id
mysqli_stmt_bind_result mysqli_stmt_fetch mysqli_stmt_num_rows
mysqli_data_seek mysqli_free_result mysqli_more_results mysqli_next_result
mysqli_store_result mysqli_character_set_name curl_init curl_setopt
curl_setopt_array curl_exec curl_getinfo curl_error curl_errno curl_close
curl_multi_init curl_multi_add_handle curl_multi_exec curl_multi_remove_handle
curl_multi_close fsockopen pfsockopen stream_socket_client stream_socket_server
gethostbyname gethostbynamel gethostbyaddr dns_get_record checkdnsrr getmxrr
ip2long long2ip inet_pton inet_ntop getallheaders apache_request_headers
http_build_query ob_start ob_end_clean ob_get_clean ob_get_contents
ob_end_flush ob_flush flush ob_get_level ob_get_status ob_implicit_flush
imagecreate imagecreatetruecolor imagecreatefromjpeg imagecreatefrompng
imagecreatefromgif imagecreatefromwebp imagecreatefromstring imagepng
imagejpeg imagegif imagewebp imagesx imagesy imagecopyresampled
imagecopyresized imagecolorallocate imagecolorallocatealpha imagefill
imagealphablending imagesavealpha getimagesize getimagesizefromstring
imagedestroy imagestring imagefilledrectangle imagecopy imagecrop
imageflip imagescale exif_read_data exif_imagetype iterator_to_array
iterator_count iterator_apply array_is_list fdiv str_increment str_decrement
mb_str_pad mb_ucfirst mb_lcfirst mb_trim mb_ltrim mb_rtrim sleep usleep
time_sleep_until time_nanosleep uniqid memory_get_usage
memory_get_peak_usage getmypid getmyuid getmygid sys_getloadavg
debug_backtrace debug_print_backtrace gc_collect_cycles gc_enable gc_disable
gc_enabled error_get_last ini_get ini_set ini_alter ini_restore
opcache_invalidate opcache_reset opcache_get_status realpath_cache_get
realpath_cache_size getenv getenv setlocale localeconv number_format
ctype_alnum ctype_alpha ctype_digit ctype_space ctype_upper ctype_lower
ctype_xdigit ctype_cntrl ctype_graph ctype_print ctype_punct mb_ereg
mb_eregi mb_regex_encoding grapheme_strlen grapheme_substr idn_to_ascii
idn_to_utf8 normalizer_normalize gettext ngettext dgettext bindtextdomain
textdomain msgfmt snmpget version_compare substr_compare strpbrk strtok
wordwrap money_format utf8_encode utf8_decode recode_string quoted_printable
escapeshellarg escapeshellcmd exec shell_exec passthru system proc_open
proc_close proc_get_status proc_terminate proc_nice popen pclose strtr fstat
mb_encode_mimeheader mb_decode_mimeheader mb_detect_order mb_parse_str
mb_get_info mb_regex_set_options openssl_pkey_get_public openssl_verify
openssl_sign openssl_pkey_new openssl_free_key openssl_get_publickey
openssl_get_privatekey openssl_pkey_export openssl_random_pseudo_bytes
openssl_encrypt openssl_decrypt openssl_digest php_sapi_name gethostname
gzencode gzdecode gzcompress gzuncompress gzdeflate gzinflate gzfile
readgzfile zlib_decode zlib_encode fnmatch pcntl_fork pcntl_waitpid
pcntl_signal pcntl_alarm pcntl_exec posix_getpid posix_kill get_cfg_var
get_current_user getlastmod getmyinode disk_free_space disk_total_space
mime_content_type finfo_open finfo_file finfo_close get_browser
parse_str parse_url http_parse_query mb_send_mail mb_convert_case
mb_str_split str_split str_repeat str_shuffle str_word_count
pack unpack stream_set_timeout stream_set_blocking stream_get_meta_data
stream_is_local stream_resolve_include_path openssl_pkey_get_private
openssl_pkey_get_details openssl_pkey_derive openssl_pkey_free
openssl_csr_new openssl_csr_sign openssl_x509_parse gzopen gzclose gzread
gzwrite gzputs gzgets gzgetc gzgetss gzrewind gzseek gztell gzeof gzpassthru deflate_init
deflate_add inflate_init inflate_add zlib_get_coding_type
sodium_crypto_sign_detached sodium_crypto_sign_verify_detached
sodium_crypto_box_keypair sodium_bin2hex sodium_hex2bin
""".split())

DEF_RE = re.compile(r"\bfunction\s+&?\s*([A-Za-z_]\w*)\s*\(")
CLASS_RE = re.compile(r"\bclass\s+([A-Za-z_]\w*)")
CALL_RE = re.compile(r"(?<![\w$>:.\-\\])([A-Za-z_]\w*)\s*\(")
INCLUDE_RE = re.compile(
    r"\b(?:include|include_once|require|require_once)\b\s*\(?\s*"
    r"(['\"])((?:(?!\1).)*)\1")


def extract_definitions(code):
    """lowercased name -> [offsets] from string-blanked code."""
    defs = {}
    for m in DEF_RE.finditer(code):
        defs.setdefault(m.group(1).lower(), []).append(m.start(1))
    return defs


def extract_classes(text):
    return {m.group(1).lower() for m in CLASS_RE.finditer(text)}


def extract_calls(code):
    """Yield (name, offset) for bare-call candidates in string-blanked code."""
    for m in CALL_RE.finditer(code):
        yield m.group(1), m.start(1)


def extract_includes(code):
    """Yield (target, offset) for literal include/require targets."""
    for m in INCLUDE_RE.finditer(code):
        yield m.group(2), m.start()
''',
    'jcode.html': r'''"""HTML extraction: inline scripts, on* handlers, asset refs, form actions."""
import re

from .scan import line_starts, line_at

_SCRIPT_RE = re.compile(r"<script\b([^>]*)>(.*?)</script\s*>", re.S | re.I)
_SRC_ATTR_RE = re.compile(r"\bsrc\s*=\s*(['\"])((?:(?!\1).)*)\1", re.I)
_HANDLER_RE = re.compile(r"\bon[a-zA-Z]+\s*=\s*(['\"])((?:(?!\1).)*)\1")
_TAG_RE = re.compile(r"<(script|link|img|source|video|audio|a|form)\b[^>]*>", re.I)
_ATTR_RE = {
    "src": re.compile(r"\bsrc\s*=\s*(['\"])((?:(?!\1).)*)\1", re.I),
    "href": re.compile(r"\bhref\s*=\s*(['\"])((?:(?!\1).)*)\1", re.I),
    "action": re.compile(r"\baction\s*=\s*(['\"])((?:(?!\1).)*)\1", re.I),
}
_TAG_ATTR = {
    "script": ("src", "asset"),
    "link": ("href", "asset"),
    "img": ("src", "asset"),
    "source": ("src", "asset"),
    "video": ("src", "asset"),
    "audio": ("src", "asset"),
    "a": ("href", "asset"),
    "form": ("action", "form-action"),
}


def extract_scripts(text):
    """Yield (code, first_line) for inline <script> blocks (no src=)."""
    starts = line_starts(text)
    for m in _SCRIPT_RE.finditer(text):
        if _SRC_ATTR_RE.search(m.group(1)):
            continue  # external script: the file itself is scanned separately
        yield m.group(2), line_at(starts, m.start(2))


def extract_handlers(text):
    """Yield (code, line) for on*= event-handler attribute values."""
    starts = line_starts(text)
    for m in _HANDLER_RE.finditer(text):
        yield m.group(2), line_at(starts, m.start(2))


def blank_script_bodies(text):
    """Replace inline <script> bodies with spaces (newlines kept).

    Browsers treat script content as raw text, not markup — so tag-shaped
    strings inside JS (e.g. "<img src='...'>") must not be read as refs.
    """
    def _blank(m):
        body = m.group(2)
        return (m.group(0)[:m.start(2) - m.start(0)]
                + "".join("\n" if c == "\n" else " " for c in body)
                + m.group(0)[m.end(2) - m.start(0):])
    return _SCRIPT_RE.sub(_blank, text)


def extract_refs(text):
    """Yield (kind, ref, line): kind is 'asset' or 'form-action'."""
    starts = line_starts(text)
    for m in _TAG_RE.finditer(text):
        attr, kind = _TAG_ATTR[m.group(1).lower()]
        am = _ATTR_RE[attr].search(m.group(0))
        if am:
            yield kind, am.group(2), line_at(starts, m.start())
''',
    'jcode.python': r'''"""Python analysis: definitions and bare-name calls, via the ast module.

The source is PARSED, never executed (SPEC §2(F)). A name counts as
defined when it is bound anywhere in the file by a def/class, an import,
an assignment (incl. walrus / for / with-as / except-as / comprehension
targets), or as a function parameter; the live `builtins` namespace is
always defined. Calls whose target is an attribute (`obj.name(...)`)
are method calls, not bare-name calls, and are never reported.
"""
import ast
import builtins

# The interpreter's own builtin namespace (print, len, range, ...).
PY_BUILTINS = set(dir(builtins))


def parse(text):
    """ast.Module for the source, or None when it does not parse."""
    try:
        return ast.parse(text)
    except (SyntaxError, ValueError, MemoryError, RecursionError):
        return None


def _target_names(target, out):
    """Names bound by an assignment/loop/comprehension target."""
    if isinstance(target, ast.Name):
        out.add(target.id)
    elif isinstance(target, (ast.Tuple, ast.List)):
        for elt in target.elts:
            _target_names(elt, out)
    elif isinstance(target, ast.Starred):
        _target_names(target.value, out)


def _arg_names(args, out):
    params = list(getattr(args, "posonlyargs", [])) + list(args.args)
    params += list(args.kwonlyargs)
    if args.vararg is not None:
        params.append(args.vararg)
    if args.kwarg is not None:
        params.append(args.kwarg)
    for a in params:
        out.add(a.arg)


def analyse(tree):
    """(defined_names, star_import, calls) for a parsed module.

    defined_names: every name bound in the file (SPEC §2(F) model —
    nesting is flattened, parameters count file-wide).
    star_import: True when the file has `from m import *` (class (F)
    is then suppressed for the file — the imported names are unknowable).
    calls: [(name, lineno)] for bare-name call sites.
    """
    defined = set()
    calls = []
    star = False
    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
            defined.add(node.name)
            _arg_names(node.args, defined)
        elif isinstance(node, ast.ClassDef):
            defined.add(node.name)
        elif isinstance(node, ast.Lambda):
            _arg_names(node.args, defined)
        elif isinstance(node, ast.Import):
            for alias in node.names:
                defined.add(alias.asname or alias.name.split(".")[0])
        elif isinstance(node, ast.ImportFrom):
            for alias in node.names:
                if alias.name == "*":
                    star = True
                else:
                    defined.add(alias.asname or alias.name)
        elif isinstance(node, ast.Assign):
            for target in node.targets:
                _target_names(target, defined)
        elif isinstance(node, (ast.AnnAssign, ast.AugAssign)):
            _target_names(node.target, defined)
        elif isinstance(node, ast.NamedExpr):
            _target_names(node.target, defined)
        elif isinstance(node, (ast.For, ast.AsyncFor)):
            _target_names(node.target, defined)
        elif isinstance(node, (ast.With, ast.AsyncWith)):
            for item in node.items:
                if item.optional_vars is not None:
                    _target_names(item.optional_vars, defined)
        elif isinstance(node, ast.ExceptHandler):
            if node.name:
                defined.add(node.name)
        elif isinstance(node, ast.comprehension):
            _target_names(node.target, defined)
        elif isinstance(node, (ast.Global, ast.Nonlocal)):
            defined.update(node.names)
        elif isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name):
                calls.append((node.func.id, node.lineno))
    return defined, star, calls
''',
    'jcode.report': r'''"""Human-readable rendering of an audit result (text + Markdown)."""

_CLASS_TITLES = {
    "undefined-js-function": "(A) JS calls to functions defined nowhere",
    "duplicate-js-definition": "(B) JS functions defined in 2+ files",
    "contract-break": "(C) Client URLs matching no server file/route",
    "missing-file": "(D) References to files that do not exist",
    "undefined-php-function": "(E) PHP calls to functions defined nowhere",
    "undefined-python-function": "(F) Python calls to functions defined nowhere",
}


def _finding_line(f):
    line = "%s:%d — %s — %s" % (f["file"], f["line"], f["name"], f["detail"])
    if f.get("hint"):
        line += "  (nearest server file: %s)" % f["hint"]
    return line


def render_text(result):
    s = result["summary"]
    scanned = ("files scanned: %d (skipped: %d too large, %d dynamic URLs"
               % (s["files_scanned"], s["skipped_big"], s["skipped_dynamic"]))
    if s.get("skipped_excluded") or s.get("skipped_minified"):
        scanned += ", %d excluded, %d minified" % (
            s.get("skipped_excluded", 0), s.get("skipped_minified", 0))
    scanned += ")"
    out = ["J-Code audit — %s" % result["project"],
           scanned,
           "findings: %d" % s["total"]]
    for cls in sorted(s["by_class"]):
        out.append("  %-28s %d" % (cls, s["by_class"][cls]))
    if not result["findings"]:
        out.append("\nCLEAN — no findings.")
        return "\n".join(out)
    current = None
    for f in result["findings"]:
        if f["class"] != current:
            current = f["class"]
            out.append("\n== %s ==" % _CLASS_TITLES.get(current, current))
        out.append("  " + _finding_line(f))
    return "\n".join(out)


def render_markdown(result):
    s = result["summary"]
    out = ["# J-Code audit report", "",
           "Project: `%s`" % result["project"], "",
           "- Files scanned: %d (skipped: %d too large, %d dynamic URLs)"
           % (s["files_scanned"], s["skipped_big"], s["skipped_dynamic"]),
           "- **Total findings: %d**" % s["total"], ""]
    for cls in sorted(s["by_class"]):
        out.append("- %s: %d" % (cls, s["by_class"][cls]))
    current = None
    for f in result["findings"]:
        if f["class"] != current:
            current = f["class"]
            out += ["", "## %s" % _CLASS_TITLES.get(current, current), ""]
        out.append("- `%s:%d` — **%s** — %s%s" % (
            f["file"], f["line"], f["name"], f["detail"],
            (" (nearest server file: `%s`)" % f["hint"]) if f.get("hint") else ""))
    if not result["findings"]:
        out.append("\nCLEAN — no findings.")
    return "\n".join(out) + "\n"
''',
    'jcode.audit': r'''"""J-Code audit: orchestrates finding classes (A)-(F) over a project.

(A) undefined-js-function    (B) duplicate-js-definition
(C) contract-break           (D) missing-file
(E) undefined-php-function   (F) undefined-python-function
"""
import difflib
import os
from urllib.parse import unquote

from . import __version__
from . import html as html_mod
from . import js as js_mod
from . import php as php_mod
from . import python as py_mod
from .scan import (MAX_FILE_BYTES, all_project_files, blank_strings,
                   iter_project_files, line_at, line_starts, prev_word,
                   read_text, strip_comments)

A = "undefined-js-function"
B = "duplicate-js-definition"
C = "contract-break"
D = "missing-file"
E = "undefined-php-function"
F = "undefined-python-function"

_SKIP_REF_PREFIXES = ("http://", "https://", "//", "#", "mailto:", "tel:",
                      "javascript:", "data:", "blob:")


def _skip_ref(ref):
    r = ref.strip()
    if not r or r == "/":
        return True
    low = r.lower()
    if low.startswith(_SKIP_REF_PREFIXES):
        return True
    if "<?" in r or "${" in r or "{{" in r or "$" in r.split("/")[-1]:
        return True
    return False


def _clean_path(ref):
    p = ref.split("?")[0].split("#")[0]
    return unquote(p).strip()


def _exists(root, rel):
    return os.path.isfile(os.path.join(root, rel))


def resolve_from(root, from_rel, ref):
    """Resolve a file reference: relative to the referrer's dir, then root."""
    p = _clean_path(ref)
    if not p:
        return None
    cands = []
    if p.startswith("/"):
        cands.append(p.lstrip("/"))
    else:
        d = os.path.dirname(from_rel)
        if d:
            cands.append(os.path.normpath(os.path.join(d, p)))
        cands.append(os.path.normpath(p))
    for c in cands:
        if c.startswith(".."):
            continue
        if _exists(root, c):
            return c
    return None


def resolve_route(root, url):
    """Resolve a client URL against the project root (+ route variants)."""
    p = _clean_path(url).lstrip("/")
    if not p:
        return None
    for c in (p, p + ".php", p.rstrip("/") + "/index.php", p + ".html"):
        if _exists(root, c):
            return c
    return None


def _nearest(target, candidates):
    hits = difflib.get_close_matches(target, candidates, n=1, cutoff=0.35)
    if hits:
        return hits[0]
    base = os.path.basename(target)
    hits = difflib.get_close_matches(
        base, [os.path.basename(c) for c in candidates], n=1, cutoff=0.5)
    if hits:
        for c in candidates:
            if os.path.basename(c) == hits[0]:
                return c
    return None


def audit_project(root, excludes=(), skip_minified=False, exclude_files=()):
    """Audit a project. excludes / skip_minified are the SPEC §7.3 CLI
    options; exclude_files is SPEC §9.1 (the tool never scans its own
    file). The defaults reproduce v0.1 behaviour exactly."""
    root = os.path.abspath(root)
    findings = []

    def add(cls, file, line, name, detail, hint=None):
        f = {"id": "", "class": cls, "file": file, "line": line,
             "name": name, "detail": detail}
        if hint:
            f["hint"] = hint
        findings.append(f)

    scan_stats = {}
    files = iter_project_files(root, excludes=excludes,
                               skip_minified=skip_minified,
                               stats=scan_stats, exclude_files=exclude_files)
    js_units = []      # (rel, raw_code, first_line)
    html_refs = []     # (rel, kind, ref, line)
    php_texts = {}     # rel -> raw text
    py_texts = {}      # rel -> raw text
    files_scanned = 0
    skipped_big = 0

    for rel, ap in files:
        if os.path.getsize(ap) > MAX_FILE_BYTES:
            skipped_big += 1
            continue
        files_scanned += 1
        text = read_text(ap)
        ext = os.path.splitext(rel)[1].lower()
        if ext == ".js":
            js_units.append((rel, text, 1))
        elif ext in (".html", ".htm"):
            for code, fl in html_mod.extract_scripts(text):
                js_units.append((rel, code, fl))
            for code, ln in html_mod.extract_handlers(text):
                js_units.append((rel, code, ln))
            for kind, ref, ln in html_mod.extract_refs(
                    html_mod.blank_script_bodies(text)):
                html_refs.append((rel, kind, ref, ln))
        elif ext == ".php":
            php_texts[rel] = text
        elif ext == ".py":
            py_texts[rel] = text

    # ---------- JS: collect definitions project-wide ----------
    js_defs = {}       # name -> [(file, line)]
    unit_data = []     # (rel, blanked_code, starts, first_line, params, defs)
    for rel, code, fl in js_units:
        clean = blank_strings(strip_comments(code))
        starts = line_starts(clean)
        defs = js_mod.extract_definitions(clean)
        for name, offs in defs.items():
            for off in offs:
                js_defs.setdefault(name, []).append(
                    (rel, fl + line_at(starts, off) - 1))
        unit_data.append((rel, clean, starts, fl,
                          js_mod.extract_params(clean), defs))

    # ---------- (B) duplicate definitions across files ----------
    for name in sorted(js_defs):
        locs = sorted(set(js_defs[name]))
        if len({f for f, _ in locs}) >= 2:
            f0, l0 = locs[0]
            where = ", ".join("%s:%d" % (f, l) for f, l in locs)
            add(B, f0, l0, name,
                "function %s() defined in %d places: %s" % (name, len(locs), where))

    # ---------- (A) undefined JS calls ----------
    for rel, clean, starts, fl, params, defs in unit_data:
        def_offsets = {(n, o) for n, offs in defs.items() for o in offs}
        for name, off in js_mod.extract_calls(clean):
            if name in js_mod.JS_KEYWORDS:
                continue
            if (name, off) in def_offsets:
                continue
            if prev_word(clean, off) in ("function", "new", "get", "set"):
                continue
            if name in js_defs or name in js_mod.JS_BUILTINS or name in params:
                continue
            add(A, rel, fl + line_at(starts, off) - 1, name,
                "call to undefined function %s()" % name)

    # ---------- (C) client URLs vs server files ----------
    client_urls = []   # (rel, url, line, dynamic)
    for rel, code, fl in js_units:
        noc = strip_comments(code)
        starts = line_starts(noc)
        for url, off, dyn in js_mod.extract_client_urls(noc):
            client_urls.append((rel, url, fl + line_at(starts, off) - 1, dyn))
    for rel, kind, ref, ln in html_refs:
        if kind == "form-action":
            client_urls.append((rel, ref, ln, False))

    php_routes = sorted(php_texts)
    skipped_dynamic = 0
    for rel, url, ln, dyn in client_urls:
        if dyn:
            skipped_dynamic += 1
            continue
        if _skip_ref(url):
            continue
        if resolve_route(root, url):
            continue
        hint = _nearest(_clean_path(url).lstrip("/"), php_routes)
        add(C, rel, ln, url,
            "client URL %s matches no server file/route" % url, hint)

    # ---------- (D) missing files referenced from HTML ----------
    for rel, kind, ref, ln in html_refs:
        if kind != "asset" or _skip_ref(ref):
            continue
        p = _clean_path(ref)
        if not p or p.endswith("/"):
            continue
        if "." not in os.path.basename(p):
            continue  # extension-less: could be a page route, not a file
        if resolve_from(root, rel, ref):
            continue
        add(D, rel, ln, ref, "referenced file not found: %s" % ref)

    # ---------- PHP: definitions, (E) calls, (D) includes ----------
    php_defs = {}
    php_clean = {}
    php_classes = set()
    for rel, text in php_texts.items():
        clean = blank_strings(strip_comments(text, lang="php"), lang="php")
        php_clean[rel] = clean
        php_classes |= php_mod.extract_classes(text)
        for name, offs in php_mod.extract_definitions(clean).items():
            php_defs.setdefault(name, []).extend(
                (rel, off) for off in offs)

    for rel, text in php_texts.items():
        clean = php_clean[rel]
        starts = line_starts(clean)
        for name, off in php_mod.extract_calls(clean):
            lname = name.lower()
            if lname in php_mod.PHP_CONSTRUCTS:
                continue
            if prev_word(clean, off) in ("function", "new"):
                continue
            if (lname in php_defs or lname in php_mod.PHP_BUILTINS
                    or lname in php_classes):
                continue
            add(E, rel, line_at(starts, off), name,
                "call to undefined PHP function %s()" % name)
        noc = strip_comments(text, lang="php")
        nstarts = line_starts(noc)
        for target, off in php_mod.extract_includes(noc):
            if target.startswith("/") or "$" in target:
                continue
            tail = noc[off:off + 200]
            close = tail.find(target) + len(target) + 1
            if tail[close:close + 4].lstrip().startswith("."):
                continue  # concatenated path -> dynamic, skip
            if resolve_from(root, rel, target):
                continue
            add(D, rel, line_at(nstarts, off), target,
                "include/require target not found: %s" % target)

    # ---------- (F) undefined Python calls ----------
    py_defs = set()
    py_units = {}      # rel -> (star_import, calls)
    for rel, text in py_texts.items():
        tree = py_mod.parse(text)
        if tree is None:
            continue  # unparseable: skipped per SPEC §2(F)
        defined, star, calls = py_mod.analyse(tree)
        py_defs |= defined
        py_units[rel] = (star, calls)
    for rel, (star, calls) in py_units.items():
        if star:
            continue  # `from m import *`: names unknowable, stay silent
        for name, line in calls:
            if name in py_defs or name in py_mod.PY_BUILTINS:
                continue
            add(F, rel, line, name,
                "call to undefined Python function %s()" % name)

    # ---------- dedupe identical call sites, sort, number, summarise ----
    seen = set()
    unique = []
    for f in findings:
        key = (f["class"], f["file"], f["line"], f["name"])
        if key not in seen:
            seen.add(key)
            unique.append(f)
    findings = unique
    order = {A: 0, B: 1, C: 2, D: 3, E: 4, F: 5}
    findings.sort(key=lambda f: (order[f["class"]], f["file"], f["line"],
                                 f["name"]))
    by_class = {}
    for i, f in enumerate(findings, 1):
        f["id"] = "F%03d" % i
        by_class[f["class"]] = by_class.get(f["class"], 0) + 1

    return {
        "tool": "jcode",
        "version": __version__,
        "project": root,
        "summary": {
            "total": len(findings),
            "by_class": by_class,
            "files_scanned": files_scanned,
            "skipped_big": skipped_big,
            "skipped_dynamic": skipped_dynamic,
            "skipped_excluded": scan_stats.get("skipped_excluded", 0),
            "skipped_minified": scan_stats.get("skipped_minified", 0),
        },
        "findings": findings,
    }
''',
    'jcode.fix': r'''"""J-Code fix: patch proposals, and (only on a scratch copy) application.

Rules (SPEC §4):
- (A)/(E)/(F) undefined functions -> real patch creating a TODO stub file.
- (D) missing file             -> real patch ONLY when exactly one file with
                                  the same basename exists elsewhere (path
                                  correction); otherwise proposal only.
- (B)/(C)                       -> proposal only (human decision).
- The audited project is NEVER modified in place by proposals.

v0.3 (SPEC §9) adds the in-place path on top of the same plan:
`plan_fixes` computes the safe-fix actions (§9.2); `apply_fixes` applies
them one at a time with .jcode-backup/ copies first, re-auditing after
each action and rolling back any action whose findings do not clear.
Only the CLI's `fix --yes` calls `apply_fixes` on a real project.
"""
import datetime
import difflib
import json
import os
import shutil

from .audit import A, B, C, D, E, F, audit_project
from .scan import all_project_files, read_text

# A stub file carrying this marker is J-Code-owned: appending new stubs
# to it is a safe fix (SPEC §9.2). Without the marker the file is
# human-owned and is never edited.
STUB_MARKER = "J-Code stubs - generated fix proposal."


def _new_file_patch(relpath, content):
    diff = difflib.unified_diff(
        [], content.splitlines(keepends=True),
        fromfile="/dev/null", tofile="b/" + relpath, lineterm="\n")
    return "".join(diff)


def _change_patch(relpath, old_content, new_content):
    diff = difflib.unified_diff(
        old_content.splitlines(keepends=True),
        new_content.splitlines(keepends=True),
        fromfile="a/" + relpath, tofile="b/" + relpath, lineterm="\n")
    return "".join(diff)


def _line_patch(relpath, line_no, old_line, new_line):
    return ("--- a/%s\n+++ b/%s\n@@ -%d,1 +%d,1 @@\n-%s\n+%s\n"
            % (relpath, relpath, line_no, line_no,
               old_line.rstrip("\n"), new_line.rstrip("\n")))


def _stub_js(names):
    lines = ["// J-Code stubs - generated fix proposal.",
             "// These functions were called but never defined in the project.",
             "// TODO(human): write the real implementations.", ""]
    for n in names:
        lines += ["function %s() {" % n,
                  "  console.warn('J-Code stub: %s() is not implemented yet');"
                  % n,
                  "}", ""]
    return "\n".join(lines)


def _stub_php(names):
    lines = ["<?php",
             "// J-Code stubs - generated fix proposal.",
             "// TODO(human): write the real implementations.", ""]
    for n in names:
        lines += ["function %s() {" % n,
                  "    // TODO: implement",
                  "    return null;",
                  "}", ""]
    return "\n".join(lines)


def _stub_python(names):
    lines = ["# J-Code stubs - generated fix proposal.",
             "# These functions were called but never defined in the project.",
             "# TODO(human): write the real implementations.", ""]
    for n in names:
        lines += ["def %s(*args, **kwargs):" % n,
                  "    # TODO: implement",
                  "    return None",
                  "", ""]
    return "\n".join(lines)


def _js_stub_block(name):
    return ("\nfunction %s() {\n"
            "  console.warn('J-Code stub: %s() is not implemented yet');\n"
            "}\n" % (name, name))


def _php_stub_block(name):
    return ("\nfunction %s() {\n"
            "    // TODO: implement\n"
            "    return null;\n"
            "}\n" % name)


def _py_stub_block(name):
    return ("\ndef %s(*args, **kwargs):\n"
            "    # TODO: implement\n"
            "    return None\n\n" % name)


_STUB_KINDS = (
    # (class, stub file, whole-file builder, append-block builder, patch name)
    (A, "jcode-stubs.js", _stub_js, _js_stub_block,
     "A-undefined-js-function--jcode-stubs.js.patch"),
    (E, "jcode-stubs.php", _stub_php, _php_stub_block,
     "E-undefined-php-function--jcode-stubs.php.patch"),
    (F, "jcode-stubs.py", _stub_python, _py_stub_block,
     "F-undefined-python-function--jcode-stubs.py.patch"),
)


def _key(f):
    """Finding identity that survives re-audits (ids renumber, §9.3)."""
    return (f["class"], f["file"], f["line"], f["name"])


def plan_fixes(project, excludes=(), skip_minified=False, exclude_files=()):
    """Audit `project` and compute the safe-fix plan (SPEC §9.2).

    Returns {"result": audit result, "actions": [...], "guidance":
    {finding_id: text}}. Each action is a dict:
      kind: "create" | "append" | "replace"
      class, file (project-relative target)
      content: full new file content        (create/append)
      line, old, new: in-line replacement   (replace)
      targets: [_key(f), ...] the findings this action must clear
      finding_ids: [ids from this audit]
      describe: one human line
    Findings with no action are proposals (see guidance)."""
    project = os.path.abspath(project)
    result = audit_project(project, excludes=excludes,
                           skip_minified=skip_minified,
                           exclude_files=exclude_files)
    findings = result["findings"]
    actions = []
    guidance = {}

    # ---- (A)/(E)/(F) undefined -> stub file (create or append) ----
    for cls, stub_rel, builder, block, _patch_name in _STUB_KINDS:
        cls_findings = [f for f in findings if f["class"] == cls]
        if not cls_findings:
            continue
        names = sorted({f["name"] for f in cls_findings})
        stub_path = os.path.join(project, stub_rel)
        if not os.path.exists(stub_path):
            content = builder(names)
            actions.append({
                "kind": "create", "class": cls, "file": stub_rel,
                "content": content,
                "targets": [_key(f) for f in cls_findings],
                "finding_ids": [f["id"] for f in cls_findings],
                "describe": "create %s with TODO stubs for %s"
                            % (stub_rel, ", ".join(names))})
            for f in cls_findings:
                guidance[f["id"]] = (
                    "patch: creates %s with a TODO stub for %s() — "
                    "write the real body." % (stub_rel, f["name"]))
        elif STUB_MARKER in read_text(stub_path):
            content = read_text(stub_path)
            if not content.endswith("\n"):
                content += "\n"
            content += "".join(block(n) for n in names)
            actions.append({
                "kind": "append", "class": cls, "file": stub_rel,
                "content": content,
                "targets": [_key(f) for f in cls_findings],
                "finding_ids": [f["id"] for f in cls_findings],
                "describe": "append TODO stubs for %s to %s"
                            % (", ".join(names), stub_rel)})
            for f in cls_findings:
                guidance[f["id"]] = (
                    "patch: appends a TODO stub for %s() to %s — "
                    "write the real body." % (f["name"], stub_rel))
        else:
            for f in cls_findings:
                guidance[f["id"]] = (
                    "proposal only: %s already exists and is not a "
                    "J-Code stub file; add a stub for %s() manually."
                    % (stub_rel, f["name"]))

    # ---- (D) missing file -> path correction when basename is unique ----
    all_files = all_project_files(project)
    for f in findings:
        if f["class"] != D:
            continue
        base = os.path.basename(f["name"].split("?")[0])
        matches = [r for r in all_files
                   if os.path.basename(r) == base and r != f["file"]]
        done = False
        if len(matches) == 1:
            src_dir = os.path.dirname(f["file"]) or "."
            new_ref = os.path.relpath(matches[0], src_dir).replace(os.sep, "/")
            src_lines = read_text(os.path.join(project, f["file"])).splitlines(
                keepends=True)
            if f["line"] - 1 < len(src_lines) and \
                    f["name"] in src_lines[f["line"] - 1]:
                actions.append({
                    "kind": "replace", "class": D, "file": f["file"],
                    "line": f["line"], "old": f["name"], "new": new_ref,
                    "targets": [_key(f)], "finding_ids": [f["id"]],
                    "describe": "point %s:%d at the existing file %s"
                                % (f["file"], f["line"], matches[0])})
                guidance[f["id"]] = ("patch: point the reference at the "
                                     "existing file %s." % matches[0])
                done = True
        if not done:
            guidance[f["id"]] = ("proposal only: no unique file named %s "
                                 "exists in the project — create or supply "
                                 "the asset, or remove the reference." % base)

    # ---- (B) and (C): proposals only ----
    for f in findings:
        if f["class"] == B:
            guidance[f["id"]] = ("proposal only: duplicated definition — a "
                                 "human picks the canonical copy and "
                                 "deletes the rest.")
        elif f["class"] == C:
            hint = (" Nearest server file: %s." % f["hint"]) \
                if f.get("hint") else ""
            guidance[f["id"]] = ("proposal only: fix the client URL or "
                                 "create the endpoint.%s" % hint)

    return {"result": result, "actions": actions, "guidance": guidance}


def generate_fixes(project, out_dir, apply_to=None, excludes=(),
                   skip_minified=False, exclude_files=()):
    """Audit `project`, write proposals+patches to out_dir.

    With apply_to: copy the project there, apply the auto patches to
    the copy, re-audit it, and include before/after summaries in the
    result. excludes / skip_minified mirror the audit options
    (SPEC §7.3) so fix proposals cover exactly the findings the audit
    reported. The audited project itself is never modified."""
    project = os.path.abspath(project)
    plan = plan_fixes(project, excludes=excludes,
                      skip_minified=skip_minified,
                      exclude_files=exclude_files)
    result = plan["result"]
    findings = result["findings"]
    actions = plan["actions"]
    guidance = plan["guidance"]
    os.makedirs(out_dir, exist_ok=True)

    patches = []   # (filename, content)
    used_names = set()
    for act in actions:
        if act["kind"] == "create":
            name = next(pn for (c, _r, _b, _bl, pn) in _STUB_KINDS
                        if c == act["class"])
            patches.append((name, _new_file_patch(act["file"],
                                                  act["content"])))
            used_names.add(name)
        elif act["kind"] == "append":
            name = next(pn for (c, _r, _b, _bl, pn) in _STUB_KINDS
                        if c == act["class"])
            old = read_text(os.path.join(project, act["file"]))
            patches.append((name, _change_patch(act["file"], old,
                                                act["content"])))
            used_names.add(name)
        elif act["kind"] == "replace":
            src_lines = read_text(
                os.path.join(project, act["file"])).splitlines(keepends=True)
            old_line = src_lines[act["line"] - 1]
            new_line = old_line.replace(act["old"], act["new"], 1)
            name = ("D-missing-file--%s.patch"
                    % act["file"].replace("/", "_"))
            if name in used_names:
                name = ("D-missing-file--%s-%d.patch"
                        % (act["file"].replace("/", "_"), act["line"]))
            patches.append((name, _line_patch(act["file"], act["line"],
                                              old_line, new_line)))
            used_names.add(name)

    for name, content in patches:
        with open(os.path.join(out_dir, name), "w", encoding="utf-8") as fh:
            fh.write(content)

    lines = ["# J-Code fix proposals", "",
             "Project: `%s`" % project, "",
             "Findings: %d. Auto-applicable patches: %d. "
             "The audited project was NOT modified." % (len(findings),
                                                        len(patches)), ""]
    for f in findings:
        lines.append("- **%s** `%s:%d` — %s — %s" % (
            f["id"], f["file"], f["line"], f["name"],
            guidance.get(f["id"], "proposal only.")))
    with open(os.path.join(out_dir, "proposals.md"), "w",
              encoding="utf-8") as fh:
        fh.write("\n".join(lines) + "\n")

    after = None
    if apply_to:
        apply_to = os.path.abspath(apply_to)
        if os.path.exists(apply_to):
            raise FileExistsError("apply-to target already exists: %s"
                                  % apply_to)
        shutil.copytree(project, apply_to)
        for act in actions:
            path = os.path.join(apply_to, act["file"])
            if act["kind"] in ("create", "append"):
                with open(path, "w", encoding="utf-8") as fh:
                    fh.write(act["content"])
            elif act["kind"] == "replace":
                src = read_text(path).splitlines(keepends=True)
                if act["old"] in src[act["line"] - 1]:
                    src[act["line"] - 1] = src[act["line"] - 1].replace(
                        act["old"], act["new"], 1)
                    with open(path, "w", encoding="utf-8") as fh:
                        fh.write("".join(src))
        after = audit_project(apply_to, excludes=excludes,
                              skip_minified=skip_minified)["summary"]

    return {"before": result["summary"], "after": after,
            "out_dir": out_dir, "patches": [n for n, _ in patches],
            "applied_to": apply_to, "actions": actions}


def apply_fixes(project, actions, excludes=(), skip_minified=False,
                exclude_files=()):
    """Apply safe-fix actions IN PLACE (SPEC §9.3) — CLI `fix --yes` only.

    Before the first change to any existing file, its original bytes
    are copied under <project>/.jcode-backup/<UTC timestamp>/; created
    files are recorded in that directory's manifest.json. Each action
    is verified by a re-audit: if its targeted findings did not all
    clear, the action is rolled back (bytes restored / file deleted)
    and reported. Returns {"before", "after", "applied",
    "rolled_back", "backup_dir"}."""
    project = os.path.abspath(project)

    def audit():
        return audit_project(project, excludes=excludes,
                             skip_minified=skip_minified,
                             exclude_files=exclude_files)

    before = audit()["summary"]
    ts = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    backup_dir = os.path.join(project, ".jcode-backup", ts)
    backed_up = {}
    created = []
    applied = []
    rolled_back = []

    def ensure_backup(rel):
        if rel in backed_up:
            return
        src = os.path.join(project, rel)
        if os.path.isfile(src):
            dst = os.path.join(backup_dir, rel)
            os.makedirs(os.path.dirname(dst), exist_ok=True)
            shutil.copyfile(src, dst)
            backed_up[rel] = dst

    for act in actions:
        rel = act["file"]
        path = os.path.join(project, rel)
        snapshot = None
        if os.path.isfile(path):
            with open(path, "rb") as fh:
                snapshot = fh.read()
        ok = True
        if act["kind"] in ("create", "append"):
            if snapshot is not None:
                ensure_backup(rel)
            with open(path, "w", encoding="utf-8") as fh:
                fh.write(act["content"])
            if snapshot is None and rel not in created:
                created.append(rel)
        elif act["kind"] == "replace":
            ensure_backup(rel)
            src = read_text(path).splitlines(keepends=True)
            if act["line"] - 1 < len(src) and \
                    act["old"] in src[act["line"] - 1]:
                src[act["line"] - 1] = src[act["line"] - 1].replace(
                    act["old"], act["new"], 1)
                with open(path, "w", encoding="utf-8") as fh:
                    fh.write("".join(src))
            else:
                ok = False
        keys = {_key(f) for f in audit()["findings"]}
        remaining = [t for t in act["targets"] if t in keys]
        entry = {"kind": act["kind"], "class": act["class"], "file": rel,
                 "describe": act["describe"]}
        if ok and not remaining:
            applied.append(entry)
        else:
            if snapshot is None:
                if os.path.exists(path):
                    os.remove(path)
                if rel in created:
                    created.remove(rel)
            else:
                with open(path, "wb") as fh:
                    fh.write(snapshot)
            entry["remaining"] = remaining
            rolled_back.append(entry)

    out_backup = None
    if backed_up or created:
        os.makedirs(backup_dir, exist_ok=True)
        manifest = {"tool": "jcode", "timestamp": ts,
                    "created": created, "modified": sorted(backed_up)}
        with open(os.path.join(backup_dir, "manifest.json"), "w",
                  encoding="utf-8") as fh:
            json.dump(manifest, fh, indent=2)
        out_backup = backup_dir

    return {"before": before, "after": audit()["summary"],
            "applied": applied, "rolled_back": rolled_back,
            "backup_dir": out_backup}
''',
    'jcode.cli': r'''"""J-Code command-line interface: `jcode audit` and `jcode fix`.

Installed as the `jcode` console command by the getjcode package
(SPEC §7); also runnable from a source checkout via ./jcode.
"""
import argparse
import json
import os
import sys

from . import __version__
from .audit import audit_project
from .fix import apply_fixes, generate_fixes
from .report import render_markdown, render_text

IGNORE_FILE = ".jcodeignore"


def _self_files(project):
    """SPEC §9.1: the running tool's own file, when it lies inside the
    audited project (a dropped-in jcode.py), is never scanned."""
    try:
        me = os.path.abspath(__file__)
        root = os.path.abspath(project)
        if os.path.isfile(me) and \
                os.path.commonpath([me, root]) == root and me != root:
            return (me,)
    except (ValueError, OSError):
        pass
    return ()


def _read_ignore_file(project):
    """Patterns from <project>/.jcodeignore (SPEC §7.3)."""
    path = os.path.join(project, IGNORE_FILE)
    patterns = []
    if os.path.isfile(path):
        with open(path, encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if line and not line.startswith("#"):
                    patterns.append(line)
    return patterns


def _scan_options(args):
    """Compose (excludes, skip_minified) from the CLI flags."""
    patterns = []
    if not getattr(args, "no_ignore", False):
        patterns += _read_ignore_file(args.project)
    patterns += list(getattr(args, "exclude", None) or [])
    return patterns, not getattr(args, "include_minified", False)


def _add_scan_flags(p):
    p.add_argument("--exclude", action="append", default=[],
                   metavar="PATTERN",
                   help="exclude files matching PATTERN (repeatable; "
                        "see SPEC §7.3 for pattern semantics)")
    p.add_argument("--no-ignore", action="store_true",
                   help="do not read the project's .jcodeignore file")
    p.add_argument("--include-minified", action="store_true",
                   help="also audit minified files (*.min.*), which are "
                        "skipped by default")


def main(argv=None):
    parser = argparse.ArgumentParser(
        prog="jcode",
        description="J-Code — find and fix errors in vibe-coded web "
                    "projects. Created by Hein Htet Aung.")
    parser.add_argument("--version", action="version",
                        version="jcode %s" % __version__)
    sub = parser.add_subparsers(dest="cmd", required=True)

    pa = sub.add_parser("audit", help="static audit of a JS+PHP+HTML+Python project")
    pa.add_argument("project")
    pa.add_argument("--json", metavar="PATH", help="write JSON findings here")
    pa.add_argument("--report", metavar="PATH",
                    help="write a Markdown report here")
    pa.add_argument("--fix", action="store_true",
                    help="also generate fix proposals (stub patches + "
                         "proposals.md) after the report")
    pa.add_argument("--out", default="jcode-fixes",
                    help="with --fix: where proposals/patches go "
                         "(default: ./jcode-fixes)")
    _add_scan_flags(pa)

    pf = sub.add_parser("fix", help="generate fix proposals, or with "
                                    "--yes apply the safe fixes in place")
    pf.add_argument("project")
    pf.add_argument("--out", default="jcode-fixes",
                    help="where proposals/patches go (default: ./jcode-fixes)")
    pf.add_argument("--apply-to", metavar="DIR",
                    help="copy the project here, apply auto patches to the "
                         "copy, and report before/after counts")
    pf.add_argument("--yes", action="store_true",
                    help="apply the safe fixes (SPEC §9.2) to the project "
                         "in place, with backups under .jcode-backup/; "
                         "without --yes, fix is a dry-run plan and "
                         "modifies nothing")
    _add_scan_flags(pf)

    args = parser.parse_args(argv)

    if not os.path.isdir(args.project):
        print("error: not a directory: %s" % args.project, file=sys.stderr)
        return 2

    excludes, skip_minified = _scan_options(args)
    self_files = _self_files(args.project)

    if args.cmd == "audit":
        result = audit_project(args.project, excludes=excludes,
                               skip_minified=skip_minified,
                               exclude_files=self_files)
        print(render_text(result))
        if args.json:
            with open(args.json, "w", encoding="utf-8") as fh:
                json.dump(result, fh, ensure_ascii=False, indent=2)
        if args.report:
            with open(args.report, "w", encoding="utf-8") as fh:
                fh.write(render_markdown(result))
        if args.fix:
            res = generate_fixes(args.project, args.out,
                                 excludes=excludes,
                                 skip_minified=skip_minified,
                                 exclude_files=self_files)
            print("fix proposals written to %s (%d patch files)"
                  % (res["out_dir"], len(res["patches"])))
        return 1 if result["findings"] else 0

    if args.cmd == "fix":
        if getattr(args, "yes", False) and getattr(args, "apply_to", None):
            print("error: --yes and --apply-to cannot be combined",
                  file=sys.stderr)
            return 2
        res = generate_fixes(args.project, args.out,
                             apply_to=getattr(args, "apply_to", None),
                             excludes=excludes,
                             skip_minified=skip_minified,
                             exclude_files=self_files)
        print("proposals written to %s (%d patch files)"
              % (res["out_dir"], len(res["patches"])))
        print("before: %d findings %s"
              % (res["before"]["total"], res["before"]["by_class"]))
        if res["after"] is not None:
            print("applied to copy: %s" % res["applied_to"])
            print("after:  %d findings %s"
                  % (res["after"]["total"], res["after"]["by_class"]))
            return 0
        actions = res["actions"]
        if getattr(args, "yes", False):
            out = apply_fixes(args.project, actions, excludes=excludes,
                              skip_minified=skip_minified,
                              exclude_files=self_files)
            for e in out["applied"]:
                print("APPLIED: %s" % e["describe"])
            for e in out["rolled_back"]:
                print("ROLLED BACK: %s (fix did not clear its findings; "
                      "original restored)" % e["describe"])
            if out["backup_dir"]:
                print("backups: %s" % out["backup_dir"])
            print("after:  %d findings %s"
                  % (out["after"]["total"], out["after"]["by_class"]))
            return 1 if out["rolled_back"] else 0
        # dry-run (the default): show the plan, modify nothing
        if actions:
            print("safe fixes that --yes would apply in place:")
            for act in actions:
                print("  would apply: %s" % act["describe"])
            print("re-run with --yes to apply these %d safe fixes "
                  "(originals are backed up to .jcode-backup/ first); "
                  "every other finding stays a proposal in proposals.md"
                  % len(actions))
        else:
            print("no safe fixes to apply — every finding is a proposal "
                  "in proposals.md (a human decision)")
        return 0

    return 2


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

import sys as _sys
import types as _types

_MODULE_ORDER = ['__init__', 'scan', 'js', 'php', 'html', 'python', 'report', 'audit', 'fix', 'cli']


def _install_jcode():
    pkg = _types.ModuleType("jcode")
    pkg.__package__ = "jcode"
    pkg.__path__ = []
    pkg.__file__ = __file__
    _sys.modules["jcode"] = pkg
    mods = {}
    for _name in _MODULE_ORDER:
        _fullname = "jcode" if _name == "__init__" else "jcode." + _name
        _m = _types.ModuleType(_fullname)
        _m.__package__ = "jcode"
        _m.__file__ = __file__
        _sys.modules[_fullname] = _m
        if _name != "__init__":
            setattr(pkg, _name, _m)
        mods[_fullname] = _m
    for _name in _MODULE_ORDER:
        _fullname = "jcode" if _name == "__init__" else "jcode." + _name
        _src = _MODULE_SOURCES[_fullname]
        exec(compile(_src, __file__ + " (" + _fullname + ")", "exec"),
             mods[_fullname].__dict__)
    return _sys.modules["jcode.cli"]


if __name__ == "__main__":
    _sys.exit(_install_jcode().main())
