export const apiStaticAnalysis = (apiSource) => {
    const warnings = [];
    // Check for state mutation attempts (APIs cannot set frontend state)
    const stateMutationPatterns = [
        /(\w+)\.value\s*=(?!=)\s*/g, // Setting .value property (but not comparing with == or ===)
        /(\w+)\.refresh\s*\(/g, // Calling component refresh
        /(\w+)\.reset\s*\(/g, // Calling component reset
        /(\w+)\.clear\s*\(/g, // Calling component clear
    ];
    for (const pattern of stateMutationPatterns) {
        const matches = [...apiSource.matchAll(pattern)];
        if (matches.length > 0) {
            const examples = matches.slice(0, 3).map((m) => m[0].trim());
            warnings.push(`CRITICAL: APIs cannot set frontend state. Found state mutation: ${examples.join(", ")}\n` +
                `APIs are backend workflows that can only READ state, never SET it.\n` +
                `State mutations must happen on the frontend via onSuccess/onError handlers.`);
            break; // Only report once
        }
    }
    // Check for placeholder/fake integration IDs
    const fakeIdPatterns = [
        /["']fake-[^"']*["']/gi,
        /["']placeholder-[^"']*["']/gi,
        /["']test-id["']/gi,
        /["']your-\w+-integration-id["']/gi,
        /["']integration-id["']/gi,
    ];
    for (const pattern of fakeIdPatterns) {
        if (pattern.test(apiSource)) {
            warnings.push(`CRITICAL: Found placeholder or fake integration ID.\n` +
                `All integration IDs must be real UUIDs from the provided integrations.\n` +
                `Never make up integration IDs - this will cause the API to fail.`);
            break;
        }
    }
    // Check SQL blocks for multiple queries
    const multipleQueriesPattern = /statement:\s*(?:`([^`]*)`|"([^"]*)")\s*[,}]/g;
    const statementMatches = [...apiSource.matchAll(multipleQueriesPattern)];
    for (const match of statementMatches) {
        const statement = match[1] || match[2];
        if (statement) {
            // Remove string literals to avoid false positives
            const cleanedStatement = statement.replace(/'[^']*'/g, "");
            const semicolons = (cleanedStatement.match(/;/g) || []).length;
            // If there are multiple semicolons (more than one query)
            if (semicolons > 1) {
                warnings.push(`WARNING: SQL statement appears to contain multiple queries (found ${semicolons} semicolons).\n` +
                    `Each SQL block can execute ONLY ONE query. Use separate blocks for multiple queries.`);
            }
        }
    }
    // Check for missing row limit in SELECT queries
    // Supports multiple SQL dialects: LIMIT N, TOP N, FETCH NEXT N ROWS ONLY
    const selectQueriesPattern = /statement:\s*(?:`([^`]*SELECT[^`]*)`|"([^"]*SELECT[^"]*)")/gi;
    const selectMatches = [...apiSource.matchAll(selectQueriesPattern)];
    for (const match of selectMatches) {
        const statement = match[1] || match[2];
        if (statement) {
            const hasLimit = /LIMIT\s+\d+/i.test(statement);
            const hasTop = /SELECT\s+TOP\s+\d+/i.test(statement);
            const hasFetch = /FETCH\s+(?:FIRST|NEXT)\s+\d+\s+ROWS?\s+ONLY/i.test(statement);
            if (!hasLimit && !hasTop && !hasFetch) {
                warnings.push(`WARNING: SQL SELECT query missing row limit clause.\n` +
                    `Always include a row limit (LIMIT N, SELECT TOP N, or FETCH NEXT N ROWS ONLY) unless the user explicitly requests otherwise.`);
                break; // Only warn once
            }
        }
    }
    // Check for browser globals in API blocks
    // Strip string literals and comments to avoid false positives
    const codeWithoutStringsAndComments = apiSource
        .replace(/\/\/[^\n]*/g, "")
        .replace(/\/\*[\s\S]*?\*\//g, "")
        .replace(/'[^'\\]*(?:\\.[^'\\]*)*'/g, "''")
        .replace(/"[^"\\]*(?:\\.[^"\\]*)*"/g, '""')
        .replace(/`[^`\\]*(?:\\.[^`\\]*)*`/g, "``");
    const browserGlobalPatterns = [
        /\bwindow\./g,
        /\bdocument\./g,
        /\blocation\./g,
        /\bnavigator\./g,
        /\bURLSearchParams\b/g,
    ];
    for (const pattern of browserGlobalPatterns) {
        if (pattern.test(codeWithoutStringsAndComments)) {
            warnings.push(`CRITICAL: Browser globals (window, document, location, navigator, URLSearchParams) are NOT available in API blocks.\n` +
                `APIs are backend workflows. Use the Global constant for runtime context instead.`);
            break;
        }
    }
    // Check for SQL injection patterns (any string interpolation in SQL statements)
    const sqlInjectionPattern = /statement:\s*(?:`[^`]*\$\{[^}]*\}[^`]*`|"[^"]*\$\{[^}]*\}[^"]*")/g;
    if (sqlInjectionPattern.test(apiSource)) {
        warnings.push(`WARNING: String interpolation detected in SQL statement.\n` +
            `Direct string interpolation in SQL can be unsafe.\n` +
            `Consider using parameterized queries or proper escaping for user inputs.`);
    }
    // Check Python blocks use string code, not arrow functions
    const pythonArrowFunctionPattern = /new\s+Python\s*\([^)]*,\s*{\s*fn:\s*\([^)]*\)\s*=>/g;
    if (pythonArrowFunctionPattern.test(apiSource)) {
        warnings.push(`CRITICAL: Python integration uses arrow function instead of string.\n` +
            `Python blocks require a STRING containing Python code in the 'fn' property.\n` +
            `Use: fn: \`def main():\\n  return "hello"\` NOT fn: () => "..."\n` +
            `Example: new Python("name", { fn: \`def main(x):\\n  return x * 2\` })`);
    }
    // Check for unsupported library imports in JavaScript blocks
    const jsBlockPattern = /new\s+JavaScript\s*\([^,]*,\s*{\s*fn:\s*(?:\([^)]*\)\s*=>)?\s*{([^}]*(?:{[^}]*}[^}]*)*)}/gs;
    const jsBlockMatches = [...apiSource.matchAll(jsBlockPattern)];
    for (const match of jsBlockMatches) {
        const jsCode = match[0];
        // Check for require() calls
        const requirePattern = /require\s*\(\s*["']([^"']+)["']\s*\)/g;
        const requireMatches = [...jsCode.matchAll(requirePattern)];
        // Check for import statements (note: these might be at top level, not in JS blocks)
        const importPattern = /import\s+(?:{[^}]+}|[^\s]+|\*\s+as\s+[^\s]+)\s+from\s+["']([^"']+)["']/g;
        const importMatches = [...jsCode.matchAll(importPattern)];
        const allImports = [
            ...requireMatches.map((m) => m[1]),
            ...importMatches.map((m) => m[1]),
        ];
        for (const moduleName of allImports) {
            // Extract base module name (handle scoped packages and subpaths)
            const baseModule = moduleName?.startsWith("@")
                ? moduleName?.split("/").slice(0, 2).join("/") // @scope/package
                : moduleName?.split("/")[0]; // package or node:module
            // Remove "node:" prefix if present
            const cleanModule = baseModule?.replace(/^node:/, "") ?? "";
            // Check if it's a supported library or Node.js built-in
            if (!SUPPORTED_JS_LIBRARIES.has(cleanModule) &&
                !NODEJS_BUILTINS.has(cleanModule)) {
                warnings.push(`CRITICAL: Unsupported library import detected: "${moduleName}"
` +
                    `JavaScript blocks only support specific libraries. Supported libraries:
` +
                    `  - Node.js built-ins
` +
                    `  - Third-party: ${Array.from(SUPPORTED_JS_LIBRARIES).join(", ")}
` +
                    `Use only these libraries in your JavaScript code.`);
                break; // Only warn once per block
            }
        }
    }
    // Check for unsupported library imports in Python blocks
    const pythonBlockPattern = /new\s+Python\s*\([^,]*,\s*{\s*fn:\s*`([^`]*)`/gs;
    const pythonBlockMatches = [...apiSource.matchAll(pythonBlockPattern)];
    for (const match of pythonBlockMatches) {
        const pythonCode = match[1];
        // Check for main() function definition
        const mainFunctionPattern = /^\s*def\s+main\s*\(/m;
        if (pythonCode && mainFunctionPattern.test(pythonCode)) {
            warnings.push(`CRITICAL: Python blocks should NOT define a main() function.\n` +
                `The Python code you provide is executed directly - there's no need for a main() function.\n` +
                `Instead of:\n` +
                `  def main(x):\n` +
                `      return x * 2\n` +
                `Just write:\n` +
                `  # Your code here\n` +
                `  result = x * 2\n` +
                `  # The last expression or variable is returned`);
        }
        // Check for import statements: "import module" or "from module import ..."
        const importPattern = /^\s*(?:from\s+([a-zA-Z_][\w.]*)\s+import|import\s+([a-zA-Z_][\w.]*))/gm;
        const importMatches = [...(pythonCode?.matchAll(importPattern) ?? [])];
        for (const importMatch of importMatches) {
            const moduleName = importMatch[1] || importMatch[2];
            if (!moduleName)
                continue;
            // Extract base module name (first part before any dots)
            const baseModule = moduleName?.split(".")[0] ?? "";
            // Check if it's a supported library or Python built-in
            // We need to check case-insensitively for some packages
            const isSupported = SUPPORTED_PYTHON_LIBRARIES.has(baseModule) ||
                SUPPORTED_PYTHON_LIBRARIES.has(baseModule.toLowerCase()) ||
                PYTHON_BUILTINS.has(baseModule);
            if (!isSupported) {
                warnings.push(`CRITICAL: Unsupported library import detected in Python block: "${moduleName}"
` +
                    `Python blocks only support specific libraries. Supported libraries:
` +
                    `  - Python built-ins
` +
                    `  - Third-party: ${Array.from(SUPPORTED_PYTHON_LIBRARIES).join(", ")}
` +
                    `Use only these libraries in your Python code.`);
                break; // Only warn once per block
            }
        }
    }
    // Check Databricks tables use three-part naming (catalog.schema.table)
    const databricksPattern = /new\s+Databricks\s*\([^)]*,\s*{\s*statement:/g;
    const databricksMatches = [...apiSource.matchAll(databricksPattern)];
    if (databricksMatches.length > 0) {
        // Extract Databricks statements to check table naming
        const databricksStatementPattern = /new\s+Databricks\s*\([^)]*,\s*{\s*statement:\s*(?:`([^`]*)`|"([^"]*)")/gi;
        const stmtMatches = [...apiSource.matchAll(databricksStatementPattern)];
        for (const match of stmtMatches) {
            const statement = match[1] || match[2];
            if (statement) {
                // Look for FROM/JOIN/INTO clauses with table names
                const tableRefPattern = /(?:FROM|JOIN|INTO)\s+([a-zA-Z_][\w.]*)/gi;
                const tableRefs = [...statement.matchAll(tableRefPattern)];
                for (const tableRef of tableRefs) {
                    const tableName = tableRef[1];
                    if (!tableName)
                        continue;
                    // Count dots to determine if it's three-part naming
                    const dotCount = (tableName.match(/\./g) || []).length;
                    if (dotCount < 2) {
                        warnings.push(`WARNING: Databricks table reference may be missing catalog/schema: "${tableName}"\n` +
                            `Databricks requires three-part naming: catalog.schema.table\n` +
                            `Example: uber.default.orders (not just "orders" or "uber.orders")\n` +
                            `The word "default" is NOT optional - it's the actual schema name.`);
                        break; // Only warn once
                    }
                }
            }
        }
    }
    return warnings;
};
// Supported third-party libraries in JavaScript blocks
const SUPPORTED_JS_LIBRARIES = new Set([
    "@notionhq/client",
    "@paralleldrive/cuid2",
    "amazon-qldb-driver-nodejs",
    "aws-sdk",
    "axios",
    "base64url",
    "bcrypt",
    "date-fns",
    "deasync",
    "esprima",
    "jmespath",
    "jsonwebtoken",
    "lodash",
    "minimist",
    "moment",
    "notion-to-md",
    "piscina",
    "xmlbuilder2",
    "xml2json",
    "webflow-api",
]);
// Supported Python libraries (import names, not pip package names)
const SUPPORTED_PYTHON_LIBRARIES = new Set([
    "Acquisition",
    "aiohttp",
    "aiosignal",
    "anthropic",
    "anyio",
    "appdirs",
    "appnope",
    "arrow",
    "asana",
    "asn1crypto",
    "asttokens",
    "async_timeout",
    "asyncio",
    "attrs",
    "AuthEncoding",
    "Authlib",
    "backcall",
    "backoff",
    "beautifulsoup4",
    "bs4",
    "bidict",
    "boto",
    "boto3",
    "botocore",
    "Brotli",
    "BTrees",
    "CacheControl",
    "cachetools",
    "certifi",
    "cffi",
    "charset_normalizer",
    "click",
    "cmake",
    "ConfigArgParse",
    "croniter",
    "cryptography",
    "cssselect",
    "cvxpy",
    "cycler",
    "Cython",
    "dataclasses_json",
    "DateTime",
    "decorator",
    "defusedxml",
    "Deprecated",
    "distro",
    "dnspython",
    "ecos",
    "et_xmlfile",
    "exceptiongroup",
    "executing",
    "ExtensionClass",
    "fake_useragent",
    "feedparser",
    "filelock",
    "firebase_admin",
    "Flask",
    "Flask_BasicAuth",
    "Flask_Cors",
    "fonttools",
    "fred",
    "fredapi",
    "frozendict",
    "frozenlist",
    "fsspec",
    "future",
    "geojson",
    "gevent",
    "geventhttpclient",
    "gocardless_pro",
    "google",
    "google_api_core",
    "google_api_python_client",
    "google_auth",
    "google_auth_httplib2",
    "google_auth_oauthlib",
    "google_cloud_bigquery",
    "google_cloud_core",
    "google_cloud_firestore",
    "google_cloud_functions",
    "google_cloud_pubsub",
    "google_cloud_storage",
    "google_crc32c",
    "google_resumable_media",
    "googleapis_common_protos",
    "graphviz",
    "greenlet",
    "grpc_google_iam_v1",
    "grpcio",
    "grpcio_status",
    "gspread",
    "h11",
    "html5lib",
    "httpcore",
    "httplib2",
    "httpx",
    "huggingface_hub",
    "idna",
    "importlib_metadata",
    "ipython",
    "isodate",
    "itsdangerous",
    "jedi",
    "jeepney",
    "Jinja2",
    "jinja2",
    "jira",
    "jmespath",
    "joblib",
    "jsondiff",
    "jsonpatch",
    "jsonpickle",
    "jsonpointer",
    "jycm",
    "kaleido",
    "keyring",
    "kiwisolver",
    "langchain",
    "langchain_community",
    "langchain_core",
    "langchain_text_splitters",
    "langchainplus_sdk",
    "langsmith",
    "locust",
    "loguru",
    "lxml",
    "MarkupSafe",
    "marshmallow",
    "marshmallow_enum",
    "matplotlib",
    "matplotlib_inline",
    "mccabe",
    "moncli",
    "msgpack",
    "multidict",
    "multipart",
    "multitasking",
    "mypy_extensions",
    "mysql",
    "nest_asyncio",
    "networkx",
    "nltk",
    "numexpr",
    "numpy",
    "oauthlib",
    "openai",
    "openapi_schema_pydantic",
    "openpyxl",
    "opentelemetry",
    "orjson",
    "oscrypto",
    "osqp",
    "packaging",
    "pandas",
    "parse",
    "parso",
    "pathspec",
    "patsy",
    "peewee",
    "Persistence",
    "persistent",
    "pexpect",
    "phonenumberslite",
    "pickleshare",
    "PIL",
    "pinecone",
    "platformdirs",
    "plotly",
    "postgresql_audit",
    "prometheus_client",
    "prompt_toolkit",
    "proto",
    "protobuf",
    "psutil",
    "psycopg2",
    "ptyprocess",
    "pure_eval",
    "pyaes",
    "pyarrow",
    "pyasn1",
    "pyasn1_modules",
    "pybind11",
    "pycodestyle",
    "pycountry",
    "pycparser",
    "pycryptodomex",
    "pydantic",
    "pydash",
    "pydot",
    "pyee",
    "Pygments",
    "pygments",
    "PyJWT",
    "pymongo",
    "pymongo_auth_aws",
    "pymsteams",
    "pyodbc",
    "pyOpenSSL",
    "pyowm",
    "pyparsing",
    "pypdf",
    "pypng",
    "pyppeteer",
    "pyquery",
    "PySocks",
    "python_barcode",
    "barcode",
    "box",
    "dateutil",
    "docx",
    "dotenv",
    "engineio",
    "gettext",
    "graphql",
    "socketio",
    "pytz",
    "pyvis",
    "yaml",
    "pyzipper",
    "pyzmq",
    "qdldl",
    "qrcode",
    "quickchart",
    "redis",
    "regex",
    "requests",
    "requests_file",
    "requests_futures",
    "requests_html",
    "requests_oauthlib",
    "requests_toolbelt",
    "roundrobin",
    "rsa",
    "s3transfer",
    "schematics",
    "sklearn",
    "scipy",
    "scs",
    "SecretStorage",
    "sgmllib3k",
    "simple_salesforce",
    "simple_websocket",
    "simplejson",
    "six",
    "SJSON",
    "slack_sdk",
    "sniffio",
    "snowflake",
    "sortedcontainers",
    "soupsieve",
    "sqlalchemy",
    "SQLAlchemy_Utils",
    "stack_data",
    "statsmodels",
    "stripe",
    "tablib",
    "tabulate",
    "Telethon",
    "telethon",
    "tenacity",
    "threadpoolctl",
    "thrift",
    "tldextract",
    "tokenizers",
    "tomli",
    "tomlkit",
    "tqdm",
    "traitlets",
    "transaction",
    "types_python_dateutil",
    "types_requests",
    "types_simplejson",
    "types_urllib3",
    "typing_inspect",
    "typing_extensions",
    "ujson",
    "uritemplate",
    "urllib3",
    "w3lib",
    "wcwidth",
    "webencodings",
    "websockets",
    "Werkzeug",
    "werkzeug",
    "wrapt",
    "wsproto",
    "xero_python",
    "yahoo_fin",
    "yarl",
    "yfinance",
    "zeep",
    "zExceptions",
    "zipp",
    "zope",
]);
// Node.js built-in modules (these are always allowed)
const NODEJS_BUILTINS = new Set([
    "assert",
    "buffer",
    "child_process",
    "cluster",
    "crypto",
    "dgram",
    "dns",
    "events",
    "fs",
    "http",
    "http2",
    "https",
    "net",
    "os",
    "path",
    "perf_hooks",
    "punycode",
    "querystring",
    "readline",
    "stream",
    "string_decoder",
    "timers",
    "tls",
    "tty",
    "url",
    "util",
    "v8",
    "vm",
    "worker_threads",
    "zlib",
]);
// Python standard library modules (these are always allowed)
const PYTHON_BUILTINS = new Set([
    "abc",
    "aifc",
    "argparse",
    "array",
    "ast",
    "asynchat",
    "asyncio",
    "asyncore",
    "atexit",
    "audioop",
    "base64",
    "bdb",
    "binascii",
    "binhex",
    "bisect",
    "builtins",
    "bz2",
    "calendar",
    "cgi",
    "cgitb",
    "chunk",
    "cmath",
    "cmd",
    "code",
    "codecs",
    "codeop",
    "collections",
    "colorsys",
    "compileall",
    "concurrent",
    "configparser",
    "contextlib",
    "contextvars",
    "copy",
    "copyreg",
    "cProfile",
    "crypt",
    "csv",
    "ctypes",
    "curses",
    "dataclasses",
    "datetime",
    "dbm",
    "decimal",
    "difflib",
    "dis",
    "distutils",
    "doctest",
    "email",
    "encodings",
    "enum",
    "errno",
    "faulthandler",
    "fcntl",
    "filecmp",
    "fileinput",
    "fnmatch",
    "fractions",
    "ftplib",
    "functools",
    "gc",
    "getopt",
    "getpass",
    "gettext",
    "glob",
    "graphlib",
    "grp",
    "gzip",
    "hashlib",
    "heapq",
    "hmac",
    "html",
    "http",
    "imaplib",
    "imghdr",
    "imp",
    "importlib",
    "inspect",
    "io",
    "ipaddress",
    "itertools",
    "json",
    "keyword",
    "lib2to3",
    "linecache",
    "locale",
    "logging",
    "lzma",
    "mailbox",
    "mailcap",
    "marshal",
    "math",
    "mimetypes",
    "mmap",
    "modulefinder",
    "msilib",
    "msvcrt",
    "multiprocessing",
    "netrc",
    "nis",
    "nntplib",
    "numbers",
    "operator",
    "optparse",
    "os",
    "ossaudiodev",
    "pathlib",
    "pdb",
    "pickle",
    "pickletools",
    "pipes",
    "pkgutil",
    "platform",
    "plistlib",
    "poplib",
    "posix",
    "posixpath",
    "pprint",
    "profile",
    "pstats",
    "pty",
    "pwd",
    "py_compile",
    "pyclbr",
    "pydoc",
    "queue",
    "quopri",
    "random",
    "re",
    "readline",
    "reprlib",
    "resource",
    "rlcompleter",
    "runpy",
    "sched",
    "secrets",
    "select",
    "selectors",
    "shelve",
    "shlex",
    "shutil",
    "signal",
    "site",
    "smtpd",
    "smtplib",
    "sndhdr",
    "socket",
    "socketserver",
    "spwd",
    "sqlite3",
    "ssl",
    "stat",
    "statistics",
    "string",
    "stringprep",
    "struct",
    "subprocess",
    "sunau",
    "symtable",
    "sys",
    "sysconfig",
    "syslog",
    "tabnanny",
    "tarfile",
    "telnetlib",
    "tempfile",
    "termios",
    "test",
    "textwrap",
    "threading",
    "time",
    "timeit",
    "token",
    "tokenize",
    "tomllib",
    "trace",
    "traceback",
    "tracemalloc",
    "tty",
    "turtle",
    "types",
    "typing",
    "unicodedata",
    "unittest",
    "urllib",
    "uu",
    "uuid",
    "venv",
    "warnings",
    "wave",
    "weakref",
    "webbrowser",
    "winreg",
    "winsound",
    "wsgiref",
    "xml",
    "xmlrpc",
    "zipapp",
    "zipfile",
    "zipimport",
    "zlib",
]);
//# sourceMappingURL=static-analysis.js.map