//! k6 script generator for OpenAPI 3.0.0 conformance testing

use crate::error::{BenchError, Result};
use std::path::{Path, PathBuf};

use super::custom::CustomConformanceConfig;

/// Configuration for conformance test generation
#[derive(Default, Clone)]
pub struct ConformanceConfig {
    /// Target base URL
    pub target_url: String,
    /// API key for security scheme tests
    pub api_key: Option<String>,
    /// Basic auth credentials (user:pass) for security scheme tests
    pub basic_auth: Option<String>,
    /// Skip TLS verification
    pub skip_tls_verify: bool,
    /// Optional category filter — None means all categories
    pub categories: Option<Vec<String>>,
    /// Optional base path prefix for all generated URLs (e.g., "/api")
    pub base_path: Option<String>,
    /// Custom headers to inject into every conformance request (e.g., auth headers).
    /// Each entry is (header_name, header_value). When a custom header matches
    /// a spec-derived header name, the custom value replaces the placeholder.
    pub custom_headers: Vec<(String, String)>,
    /// Output directory for the conformance report (absolute path).
    /// Used to write `conformance-report.json` to a deterministic location
    /// so the CLI can find it after k6 execution.
    pub output_dir: Option<PathBuf>,
    /// When true, test ALL operations for method/response/body categories
    /// instead of just one representative per feature check name.
    pub all_operations: bool,
    /// Optional path to a YAML file with custom conformance checks
    pub custom_checks_file: Option<PathBuf>,
    /// Delay in milliseconds between consecutive conformance requests.
    /// Useful when testing against rate-limited APIs. Default: 0 (no delay).
    pub request_delay_ms: u64,
    /// Optional regex to filter custom checks by name or path.
    /// Only checks whose name or path matches the regex are included.
    pub custom_filter: Option<String>,
    /// When true, export all request/response pairs to a JSON file
    /// in the output directory (`conformance-requests.json`).
    pub export_requests: bool,
    /// When true, validate each request against the OpenAPI spec before
    /// sending and report violations to `conformance-request-violations.json`.
    pub validate_requests: bool,
}

impl ConformanceConfig {
    /// Check if a category should be included based on the filter
    pub fn should_include_category(&self, category: &str) -> bool {
        match &self.categories {
            None => true,
            Some(cats) => cats.iter().any(|c| c.eq_ignore_ascii_case(category)),
        }
    }

    /// Returns true if custom headers are configured
    pub fn has_custom_headers(&self) -> bool {
        !self.custom_headers.is_empty()
    }

    /// Returns true if custom headers contain a Cookie header.
    /// When true, k6's automatic cookie jar should be disabled to prevent
    /// duplicate cookies on subsequent requests.
    pub fn has_cookie_header(&self) -> bool {
        self.custom_headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("cookie"))
    }

    /// Format custom headers as a JS object literal string
    pub fn custom_headers_js_object(&self) -> String {
        let entries: Vec<String> = self
            .custom_headers
            .iter()
            .map(|(k, v)| format!("'{}': '{}'", k, v.replace('\'', "\\'")))
            .collect();
        format!("{{ {} }}", entries.join(", "))
    }

    /// Generate a k6 group block for custom checks, if configured.
    /// Returns `Ok(None)` if no custom checks file is configured.
    /// Respects `custom_filter` to include only matching checks.
    ///
    /// Round 39 (#79) — returns BOTH the init-scope code (e.g.
    /// `const __file_0 = open('/path', 'b')` for file uploads) and
    /// the group body. The caller splices `init_code` near the top of
    /// the script (after `BASE_URL`, before `export default
    /// function`) and `group_body` inside the default function. k6
    /// requires `open()` to live at init scope.
    pub fn generate_custom_group(
        &self,
    ) -> Result<Option<crate::conformance::custom::K6CustomEmit>> {
        let path = match &self.custom_checks_file {
            Some(p) => p,
            None => return Ok(None),
        };
        let mut config = CustomConformanceConfig::from_file(path)?;
        if config.custom_checks.is_empty() {
            return Ok(None);
        }

        // Apply regex filter if provided
        if let Some(ref pattern) = self.custom_filter {
            let re = regex::Regex::new(pattern).map_err(|e| {
                BenchError::Other(format!("Invalid --conformance-custom-filter regex: {}", e))
            })?;
            let total = config.custom_checks.len();
            config.custom_checks.retain(|c| re.is_match(&c.name) || re.is_match(&c.path));
            tracing::info!(
                "Custom check filter: {}/{} checks matched pattern",
                config.custom_checks.len(),
                total
            );
            if config.custom_checks.is_empty() {
                return Ok(None);
            }
        }

        Ok(Some(config.emit_k6_with_options(
            "BASE_URL",
            &self.custom_headers,
            self.export_requests,
        )))
    }

    /// Returns the effective base URL with base_path appended.
    /// Handles trailing/leading slash normalization to avoid double slashes.
    /// Always trims trailing slashes from the result so that `${BASE_URL}/path`
    /// never produces `//path`.
    pub fn effective_base_url(&self) -> String {
        let base = match &self.base_path {
            None => self.target_url.trim_end_matches('/').to_string(),
            Some(bp) if bp.is_empty() => self.target_url.trim_end_matches('/').to_string(),
            Some(bp) => {
                let url = self.target_url.trim_end_matches('/');
                let path = if bp.starts_with('/') {
                    bp.as_str()
                } else {
                    return format!("{}/{}", url, bp).trim_end_matches('/').to_string();
                };
                format!("{}{}", url, path).trim_end_matches('/').to_string()
            }
        };
        base
    }
}

/// Generates k6 scripts for OpenAPI 3.0.0 conformance testing
pub struct ConformanceGenerator {
    config: ConformanceConfig,
}

impl ConformanceGenerator {
    pub fn new(config: ConformanceConfig) -> Self {
        Self { config }
    }

    /// Generate the conformance test k6 script
    pub fn generate(&self) -> Result<String> {
        let mut script = String::with_capacity(16384);

        // Imports
        script.push_str("import http from 'k6/http';\n");
        script.push_str("import { check, group } from 'k6';\n");
        if self.config.request_delay_ms > 0 {
            script.push_str("import { sleep } from 'k6';\n");
        }
        script.push('\n');

        // Tell k6 that all HTTP status codes are "expected" in conformance mode.
        // Without this, k6 counts 4xx responses (e.g. intentional 404 tests) as
        // http_req_failed errors, producing a misleading error rate percentage.
        script.push_str(
            "http.setResponseCallback(http.expectedStatuses({ min: 100, max: 599 }));\n\n",
        );

        // Options: 1 VU, 1 iteration (functional test, not load test)
        script.push_str("export const options = {\n");
        script.push_str("  vus: 1,\n");
        script.push_str("  iterations: 1,\n");
        if self.config.skip_tls_verify {
            script.push_str("  insecureSkipTLSVerify: true,\n");
        }
        script.push_str("  thresholds: {\n");
        script.push_str("    checks: ['rate>0'],\n");
        script.push_str("  },\n");
        script.push_str("};\n\n");

        // Base URL (includes base_path if configured)
        script.push_str(&format!("const BASE_URL = '{}';\n\n", self.config.effective_base_url()));

        // Delay between requests (seconds) to avoid rate limiting
        if self.config.request_delay_ms > 0 {
            script.push_str(&format!(
                "const REQUEST_DELAY = {:.3};\n\n",
                self.config.request_delay_ms as f64 / 1000.0
            ));
        }

        // Helper: JSON headers
        script.push_str("const JSON_HEADERS = { 'Content-Type': 'application/json' };\n\n");

        // Round 39 (#79) — emit init-scope code (e.g. `open()` calls
        // for file uploads in custom checks) here, before any
        // function declarations. k6 requires `open()` to live at
        // script init scope; placing it inside `export default
        // function` is a runtime ReferenceError.
        let custom_emit = self.config.generate_custom_group()?;
        if let Some(emit) = &custom_emit {
            if !emit.init_code.is_empty() {
                script.push_str("// Round 39 (#79) — preloaded upload bytes for custom checks\n");
                script.push_str(&emit.init_code);
                script.push('\n');
            }
        }

        // Failure detail collector — logs req/res info for failed checks via console.log
        script.push_str("function __captureFailure(checkName, res, expected) {\n");
        script.push_str("  let bodyStr = '';\n");
        script.push_str("  try { if (res.body) { const __n = res.body.length; bodyStr = res.body.substring(0, 65536); if (__n > 65536) bodyStr = bodyStr + ' <truncated at 65536 bytes; full body was ' + __n + ' bytes>'; } else { bodyStr = ''; } } catch(e) { bodyStr = '<unreadable>'; }\n");
        script.push_str("  let reqHeaders = {};\n");
        script.push_str(
            "  if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
        );
        script.push_str("  let reqBody = '';\n");
        script.push_str("  if (res.request && res.request.body) { try { const __m = res.request.body.length; reqBody = res.request.body.substring(0, 65536); if (__m > 65536) reqBody = reqBody + ' <truncated at 65536 bytes; full body was ' + __m + ' bytes>'; } catch(e) {} }\n");
        script.push_str("  console.log('MOCKFORGE_FAILURE:' + JSON.stringify({\n");
        script.push_str("    check: checkName,\n");
        script.push_str("    request: {\n");
        script.push_str("      method: res.request ? res.request.method : 'unknown',\n");
        script.push_str("      url: res.request ? res.request.url : res.url || 'unknown',\n");
        script.push_str("      headers: reqHeaders,\n");
        script.push_str("      body: reqBody,\n");
        script.push_str("    },\n");
        script.push_str("    response: {\n");
        script.push_str("      status: res.status,\n");
        script.push_str("      headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 20)) : {},\n");
        script.push_str("      body: bodyStr,\n");
        script.push_str("    },\n");
        script.push_str("    expected: expected,\n");
        script.push_str("  }));\n");
        script.push_str("}\n\n");

        // Request/response capture for --export-requests (uses console.log since
        // k6's handleSummary runs in a separate JS context with no access to
        // module-level variables — the CLI parses the output log after k6 exits).
        //
        // Round 44 (#79) — Srikanth on 0.3.188: he reported `MOCKFORGE_UPLOAD_PARTS`
        // appearing in k6-output.log but `MOCKFORGE_EXCHANGE` for the same check
        // missing entirely from `conformance-requests.json` / `-failure-details.json`.
        // The most likely failure mode is an exception inside `JSON.stringify`
        // (multipart bodies can include bytes that produce surrogate-half strings
        // k6's stringifier chokes on; very large request URLs can also bust k6's
        // console-line length). Wrap the entire payload build + stringify in a
        // try/catch and ALWAYS emit a fallback `MOCKFORGE_EXCHANGE` line — even
        // when stringify fails — so the request never silently disappears from
        // the export. The fallback carries `check`, method, URL, status, and an
        // `_export_error` flag so a downstream consumer can tell a degraded
        // entry from a clean one.
        if self.config.export_requests {
            script.push_str("function __captureExchange(checkName, res) {\n");
            script.push_str("  try {\n");
            script.push_str("    let bodyStr = '';\n");
            script.push_str("    try { if (res.body) { const __n = res.body.length; bodyStr = res.body.substring(0, 65536); if (__n > 65536) bodyStr = bodyStr + ' <truncated at 65536 bytes; full body was ' + __n + ' bytes>'; } else { bodyStr = ''; } } catch(e) { bodyStr = '<unreadable>'; }\n");
            script.push_str("    let reqHeaders = {};\n");
            script.push_str(
                "    if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
            );
            // Round 41 (#79) — Srikanth on 0.3.185: "When run without
            // Spec the export request file has blank entry". k6's
            // `res.request.body` is empty for multipart uploads (k6
            // serialises the form internally and the JS-side body
            // string is null). Fall back to a content-type-derived
            // summary so the export at least surfaces "multipart/form-data; N parts"
            // instead of an empty string. Real bodies still surface
            // unchanged.
            // Round 46 (#79) — Srikanth on 0.3.190: a 13MB multipart
            // upload landed `[]` in conformance-requests.json even
            // though `MOCKFORGE_EXCHANGE:` was present in the k6 log.
            // Root cause: k6's logfmt encoder doesn't fully escape
            // binary bytes that JSON.stringify emits as raw chars
            // (control codepoints above 0x1F, surrogate halves, etc),
            // so the resulting line wasn't valid JSON-in-logfmt and the
            // parser dropped it on the floor. Fix: when Content-Type is
            // `multipart/`, NEVER include raw body bytes in the export.
            // Walk the part boundaries server-side (in JS) and emit a
            // structured summary list of `{name, filename, contentType,
            // bytes}` per part, then a one-line preamble showing the
            // boundary + total byte count. This survives JSON-stringify
            // + logfmt cleanly and gives the user a strictly more
            // useful view than the raw envelope ever did.
            script.push_str("    let reqBody = '';\n");
            script.push_str("    {\n");
            script.push_str(
                "      const ct = (reqHeaders['Content-Type'] || reqHeaders['content-type'] || '').toString();\n",
            );
            script.push_str("      const isMultipart = ct.startsWith('multipart/');\n");
            script.push_str(
                "      if (isMultipart && res.request && res.request.body) {\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20try {\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  const raw = res.request.body;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  let totalBytes = raw.length;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  let envelopeBytes = 0;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  const boundaryMatch = ct.match(/boundary=([^;]+)/);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  const boundary = boundaryMatch ? boundaryMatch[1].replace(/^\"|\"$/g, '') : '';\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  const parts = [];\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  if (boundary) {\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20    const sep = '--' + boundary;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20    let cursor = raw.indexOf(sep);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20    while (cursor !== -1 && parts.length < 100) {\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      const next = raw.indexOf(sep, cursor + sep.length);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      if (next === -1) break;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      const slice = raw.substring(cursor + sep.length, next);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      const headerEnd = slice.indexOf('\\r\\n\\r\\n');\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      const partHeaders = headerEnd === -1 ? slice : slice.substring(0, headerEnd);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      const partBody = headerEnd === -1 ? '' : slice.substring(headerEnd + 4);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      // Round 50 #79 — the envelope (sep + part headers + the\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      // header/body CRLFs + the trailing CRLF) is pure ASCII, so\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      // its .length equals its byte count even when binary part\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      // bodies mangle raw.length. sep=--boundary; +4 = header\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      // separator CRLFCRLF; +2 = trailing CRLF after the body.\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      envelopeBytes += sep.length + partHeaders.length + 6;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      const nameMatch = partHeaders.match(/name=\"([^\"]+)\"/);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      const filenameMatch = partHeaders.match(/filename=\"([^\"]+)\"/);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      const partCtMatch = partHeaders.match(/Content-Type:\\s*([^\\r\\n]+)/i);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      parts.push({\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20        name: nameMatch ? nameMatch[1] : '',\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20        filename: filenameMatch ? filenameMatch[1] : '',\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20        contentType: partCtMatch ? partCtMatch[1].trim() : '',\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20        bytes: Math.max(0, partBody.length - 2),\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      });\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20      cursor = next;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20    }\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20    // Closing boundary: --boundary--CRLF.\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20    if (parts.length) { envelopeBytes += sep.length + 4; }\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  }\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // Round 47 #79 — overlay accurate on-disk byte counts from\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // the per-check size map written at init scope; falls back\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // to the JS-string-derived bytes when no entry exists.\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // Round 48 #79 — Srikanth on 0.3.192: per-file counts were\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // exact but the total was still off because we kept using\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // raw.length (UTF-16 code units). Recompute totalBytes as\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // the SUM of per-part bytes once they've been overlaid; only\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // every part's true byte count came from disk does the sum\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // equal the actual upload size (the multipart envelope\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // overhead bytes stay reported as the raw.length delta).\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  const __mfSizes = (globalThis.__mfUploadSizes || {})[checkName] || {};\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  let __allKnown = parts.length > 0;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  parts.forEach(function (p) { if (typeof __mfSizes[p.name] === 'number') { p.bytes = __mfSizes[p.name]; } else { __allKnown = false; } });\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  const partsTotal = parts.reduce(function (acc, p) { return acc + p.bytes; }, 0);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  if (__allKnown) totalBytes = partsTotal;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // Round 49 #79 — Srikanth on 0.3.193 asked why our proxy\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // counted 57998271 bytes vs mockforge's 57996316 (disk\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // sum). The diff is the multipart envelope (boundaries,\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // per-part Content-Disposition / Content-Type lines,\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // CRLFs, the final closing boundary). Surface both:\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // `total` stays the disk-sum payload (what a receiver\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // writes back to disk); `wire` adds the envelope so\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // packet captures / proxy byte counters match.\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // Round 50 #79 — Srikanth on 0.3.194 saw wire (56344432)\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // come out SMALLER than total (57996316). raw.length is a\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // UTF-8-decoded JS string, so binary part bytes collapse\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // and it UNDERcounts. The envelope is only ~2KB for 9\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // parts, so wire can never be less than total. Compute it\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  // from the disk-accurate payload plus the ASCII envelope.\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  const wireBytes = __allKnown ? (partsTotal + envelopeBytes) : ((typeof raw === 'string' && raw.length) ? raw.length : totalBytes);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  const summary = parts.map(function (p) { return '\\'' + p.name + '\\':\\'' + p.filename + '\\' (' + p.contentType + ', ' + p.bytes + ' bytes)'; }).join(', ');\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  reqBody = '<multipart/form-data; boundary=' + boundary + '; ' + parts.length + ' part(s); total ' + totalBytes + ' bytes (wire ' + wireBytes + ' bytes w/ envelope): ' + summary + '>';\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20} catch (e) {\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20  reqBody = '<multipart upload; summary failed: ' + (e && e.message ? e.message : 'unknown') + '>';\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20}\n\
                 \x20\x20\x20\x20\x20\x20} else if (isMultipart) {\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20reqBody = '<multipart upload; body bytes not surfaced by k6 res.request.body>';\n\
                 \x20\x20\x20\x20\x20\x20} else if (res.request && res.request.body) {\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20try { const __m = res.request.body.length; reqBody = res.request.body.substring(0, 65536); if (__m > 65536) reqBody = reqBody + ' <truncated at 65536 bytes; full body was ' + __m + ' bytes>'; } catch (e) {}\n\
                 \x20\x20\x20\x20\x20\x20}\n\
                 \x20\x20\x20\x20}\n",
            );
            // Round 47 (#79) — emit a separate MOCKFORGE_NETWORK_EVENT
            // line when the request never completed (k6 returns
            // status=0 with an error_code/error string for connect /
            // tls / timeout failures). The CLI executor harvests these
            // into `conformance-network-events.json` for the k6 path,
            // matching the native + self-test paths.
            script.push_str(
                "    if (res && res.status === 0) {\n\
                 \x20\x20\x20\x20\x20\x20const ec = (res.error_code != null) ? res.error_code : 0;\n\
                 \x20\x20\x20\x20\x20\x20const em = (res.error != null) ? String(res.error) : '';\n\
                 \x20\x20\x20\x20\x20\x20// k6 error_code ranges: 1200s = TCP/DNS, 1300s = TLS, 1400s = timeout, 1500s = HTTP/2, others. Map coarsely.\n\
                 \x20\x20\x20\x20\x20\x20let kind = 'other';\n\
                 \x20\x20\x20\x20\x20\x20if (ec >= 1200 && ec < 1300) kind = 'connect';\n\
                 \x20\x20\x20\x20\x20\x20else if (ec >= 1300 && ec < 1400) kind = 'tls';\n\
                 \x20\x20\x20\x20\x20\x20else if (ec >= 1400 && ec < 1500) kind = 'timeout';\n\
                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('eof') !== -1) kind = 'connect';\n                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('timeout') !== -1) kind = 'timeout';\n\
                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('tls') !== -1) kind = 'tls';\n\
                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('connect') !== -1 || em.toLowerCase().indexOf('refused') !== -1) kind = 'connect';\n\
                 \x20\x20\x20\x20\x20\x20console.log('MOCKFORGE_NETWORK_EVENT:' + JSON.stringify({\n\
                 \x20\x20\x20\x20\x20\x20  timestamp: new Date().toISOString(),\n\
                 \x20\x20\x20\x20\x20\x20  check: checkName,\n\
                 \x20\x20\x20\x20\x20\x20  method: res.request ? res.request.method : 'unknown',\n\
                 \x20\x20\x20\x20\x20\x20  url: res.request ? res.request.url : res.url || 'unknown',\n\
                 \x20\x20\x20\x20\x20\x20  kind: kind,\n\
                 \x20\x20\x20\x20\x20\x20  error_code: ec,\n\
                 \x20\x20\x20\x20\x20\x20  message: em,\n\
                 \x20\x20\x20\x20\x20\x20}));\n\
                 \x20\x20\x20\x20}\n",
            );
            script.push_str("    console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
            script.push_str("      check: checkName,\n");
            script.push_str("      request: {\n");
            script.push_str("        method: res.request ? res.request.method : 'unknown',\n");
            script.push_str("        url: res.request ? res.request.url : res.url || 'unknown',\n");
            script.push_str("        headers: reqHeaders,\n");
            script.push_str("        body: reqBody,\n");
            script.push_str("      },\n");
            script.push_str("      response: {\n");
            script.push_str("        status: res.status,\n");
            script.push_str("        headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 30)) : {},\n");
            script.push_str("        body: bodyStr,\n");
            script.push_str("      },\n");
            script.push_str("    }));\n");
            script.push_str("  } catch (e) {\n");
            // Fallback path: still emit SOMETHING the parser can pick up
            // so the request doesn't vanish from the export. Stays short
            // on purpose — bigger payload was what tripped the primary
            // path.
            script.push_str("    try {\n");
            script.push_str("      console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
            script.push_str("        check: checkName,\n");
            script.push_str("        request: {\n");
            script.push_str(
                "          method: (res && res.request) ? res.request.method : 'unknown',\n",
            );
            script.push_str("          url: (res && res.request) ? res.request.url : (res && res.url) || 'unknown',\n");
            script.push_str("          headers: {},\n");
            script.push_str("          body: '<exchange capture failed: ' + (e && e.message ? e.message : 'unknown error') + '>',\n");
            script.push_str("        },\n");
            script.push_str("        response: {\n");
            script.push_str("          status: (res && res.status) || 0,\n");
            script.push_str("          headers: {},\n");
            script.push_str("          body: '',\n");
            script.push_str("        },\n");
            script.push_str("        _export_error: (e && e.message) ? e.message : String(e),\n");
            script.push_str("      }));\n");
            script.push_str("    } catch (e2) {\n");
            // Last-resort: a hand-rolled JSON string so even if a
            // second stringify fails, we still flag the failure.
            script.push_str("      console.log('MOCKFORGE_EXCHANGE:{\"check\":\"' + checkName + '\",\"request\":{\"method\":\"unknown\",\"url\":\"unknown\",\"headers\":{},\"body\":\"\"},\"response\":{\"status\":0,\"headers\":{},\"body\":\"\"},\"_export_error\":\"double-fault\"}');\n");
            script.push_str("    }\n");
            script.push_str("  }\n");
            script.push_str("}\n\n");
        }

        // Default function
        script.push_str("export default function () {\n");

        if self.config.has_cookie_header() {
            script.push_str(
                "  // Clear cookie jar to prevent server Set-Cookie from duplicating custom Cookie header\n",
            );
            script.push_str("  http.cookieJar().clear(BASE_URL);\n\n");
        }

        // Helper to insert a delay between groups when --conformance-delay is set
        let delay_between = if self.config.request_delay_ms > 0 {
            "  sleep(REQUEST_DELAY);\n".to_string()
        } else {
            String::new()
        };

        // Round 39 (#79) — Srikanth on 0.3.183: "In the exported
        // request I see it is sending request to
        // api/conformance/params/hello and some other URLs". When the
        // user passed `--conformance-custom` without `--spec`, the
        // generator still emitted the 47 built-in reference checks
        // against `/conformance/...` paths, which 404 on a real
        // target. Skip them when custom checks are the only input —
        // matching the native executor's `custom_only` branch.
        let custom_only = self.config.custom_checks_file.is_some()
            && !self.config.target_url.is_empty()
            // Reference checks ARE the right answer when the user
            // explicitly listed categories with --conformance-category.
            && self.config.categories.is_none();
        if !custom_only {
            if self.config.should_include_category("Parameters") {
                self.generate_parameters_group(&mut script);
                script.push_str(&delay_between);
            }
            if self.config.should_include_category("Request Bodies") {
                self.generate_request_bodies_group(&mut script);
                script.push_str(&delay_between);
            }
            if self.config.should_include_category("Schema Types") {
                self.generate_schema_types_group(&mut script);
                script.push_str(&delay_between);
            }
            if self.config.should_include_category("Composition") {
                self.generate_composition_group(&mut script);
                script.push_str(&delay_between);
            }
            if self.config.should_include_category("String Formats") {
                self.generate_string_formats_group(&mut script);
                script.push_str(&delay_between);
            }
            if self.config.should_include_category("Constraints") {
                self.generate_constraints_group(&mut script);
                script.push_str(&delay_between);
            }
            if self.config.should_include_category("Response Codes") {
                self.generate_response_codes_group(&mut script);
                script.push_str(&delay_between);
            }
            if self.config.should_include_category("HTTP Methods") {
                self.generate_http_methods_group(&mut script);
                script.push_str(&delay_between);
            }
            if self.config.should_include_category("Content Types") {
                self.generate_content_negotiation_group(&mut script);
                script.push_str(&delay_between);
            }
            if self.config.should_include_category("Security") {
                self.generate_security_group(&mut script);
            }
        }

        // Custom checks from YAML file — round 39: we already called
        // `generate_custom_group()` above to emit init-scope code, so
        // here we just splice the group body inside the default
        // function.
        if let Some(emit) = custom_emit {
            script.push_str(&emit.group_body);
        }

        script.push_str("}\n\n");

        // handleSummary for conformance report output
        self.generate_handle_summary(&mut script);

        Ok(script)
    }

    /// Write the generated script to a file
    pub fn write_script(&self, path: &Path) -> Result<()> {
        let script = self.generate()?;
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(path, script)
            .map_err(|e| BenchError::Other(format!("Failed to write conformance script: {}", e)))
    }

    /// Returns a JS expression for merging custom headers with provided headers.
    /// If no custom headers, returns the input as-is.
    /// If custom headers exist, wraps with Object.assign using inline header object.
    fn merge_with_custom_headers(&self, headers_expr: &str) -> String {
        if self.config.has_custom_headers() {
            format!(
                "Object.assign({{}}, {}, {})",
                headers_expr,
                self.config.custom_headers_js_object()
            )
        } else {
            headers_expr.to_string()
        }
    }

    /// Emit a GET request with optional custom headers merged in.
    fn emit_get(&self, script: &mut String, url: &str, extra_headers: Option<&str>) {
        let has_custom = self.config.has_custom_headers();
        let custom_obj = self.config.custom_headers_js_object();
        match (extra_headers, has_custom) {
            (None, false) => {
                script.push_str(&format!("      let res = http.get(`{}`);\n", url));
            }
            (None, true) => {
                script.push_str(&format!(
                    "      let res = http.get(`{}`, {{ headers: {} }});\n",
                    url, custom_obj
                ));
            }
            (Some(hdrs), false) => {
                script.push_str(&format!(
                    "      let res = http.get(`{}`, {{ headers: {} }});\n",
                    url, hdrs
                ));
            }
            (Some(hdrs), true) => {
                script.push_str(&format!(
                    "      let res = http.get(`{}`, {{ headers: Object.assign({{}}, {}, {}) }});\n",
                    url, hdrs, custom_obj
                ));
            }
        }
        self.maybe_clear_cookie_jar(script);
        self.maybe_capture_exchange(script);
    }

    /// Emit a POST/PUT/PATCH request with optional custom headers merged in.
    fn emit_post_like(
        &self,
        script: &mut String,
        method: &str,
        url: &str,
        body: &str,
        headers_expr: &str,
    ) {
        let merged = self.merge_with_custom_headers(headers_expr);
        script.push_str(&format!(
            "      let res = http.{}(`{}`, {}, {{ headers: {} }});\n",
            method, url, body, merged
        ));
        self.maybe_clear_cookie_jar(script);
        self.maybe_capture_exchange(script);
    }

    /// Emit a DELETE/HEAD/OPTIONS request with optional custom headers.
    fn emit_no_body(&self, script: &mut String, method: &str, url: &str) {
        if self.config.has_custom_headers() {
            script.push_str(&format!(
                "      let res = http.{}(`{}`, {{ headers: {} }});\n",
                method,
                url,
                self.config.custom_headers_js_object()
            ));
        } else {
            script.push_str(&format!("      let res = http.{}(`{}`);\n", method, url));
        }
        self.maybe_clear_cookie_jar(script);
        self.maybe_capture_exchange(script);
    }

    /// Emit `__captureExchange` call when `--export-requests` is enabled.
    fn maybe_capture_exchange(&self, script: &mut String) {
        if self.config.export_requests {
            script.push_str(
                "      if (typeof __captureExchange === 'function') __captureExchange('', res);\n",
            );
        }
    }

    /// Emit cookie jar clearing after a request when custom Cookie headers are used.
    /// Prevents k6's internal cookie jar from re-sending server Set-Cookie values
    /// alongside the custom Cookie header on subsequent requests.
    fn maybe_clear_cookie_jar(&self, script: &mut String) {
        if self.config.has_cookie_header() {
            script.push_str("      http.cookieJar().clear(BASE_URL);\n");
        }
    }

    fn generate_parameters_group(&self, script: &mut String) {
        script.push_str("  group('Parameters', function () {\n");

        // Path param: string
        script.push_str("    {\n");
        self.emit_get(script, "${BASE_URL}/conformance/params/hello", None);
        script.push_str(
            "      check(res, { 'param:path:string': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // Path param: integer
        script.push_str("    {\n");
        self.emit_get(script, "${BASE_URL}/conformance/params/42", None);
        script.push_str(
            "      check(res, { 'param:path:integer': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // Query param: string
        script.push_str("    {\n");
        self.emit_get(script, "${BASE_URL}/conformance/params/query?name=test", None);
        script.push_str(
            "      check(res, { 'param:query:string': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // Query param: integer
        script.push_str("    {\n");
        self.emit_get(script, "${BASE_URL}/conformance/params/query?count=10", None);
        script.push_str(
            "      check(res, { 'param:query:integer': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // Query param: array
        script.push_str("    {\n");
        self.emit_get(script, "${BASE_URL}/conformance/params/query?tags=a&tags=b", None);
        script.push_str(
            "      check(res, { 'param:query:array': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // Header param
        script.push_str("    {\n");
        self.emit_get(
            script,
            "${BASE_URL}/conformance/params/header",
            Some("{ 'X-Custom-Param': 'test-value' }"),
        );
        script.push_str(
            "      check(res, { 'param:header': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // Cookie param
        script.push_str("    {\n");
        script.push_str("      let jar = http.cookieJar();\n");
        script.push_str("      jar.set(BASE_URL, 'session', 'abc123');\n");
        self.emit_get(script, "${BASE_URL}/conformance/params/cookie", None);
        script.push_str(
            "      check(res, { 'param:cookie': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        script.push_str("  });\n\n");
    }

    fn generate_request_bodies_group(&self, script: &mut String) {
        script.push_str("  group('Request Bodies', function () {\n");

        // JSON body
        script.push_str("    {\n");
        self.emit_post_like(
            script,
            "post",
            "${BASE_URL}/conformance/body/json",
            "JSON.stringify({ name: 'test', value: 42 })",
            "JSON_HEADERS",
        );
        script.push_str(
            "      check(res, { 'body:json': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // Form-urlencoded body
        script.push_str("    {\n");
        if self.config.has_custom_headers() {
            script.push_str(&format!(
                "      let res = http.post(`${{BASE_URL}}/conformance/body/form`, {{ field1: 'value1', field2: 'value2' }}, {{ headers: {} }});\n",
                self.config.custom_headers_js_object()
            ));
        } else {
            script.push_str(
                "      let res = http.post(`${BASE_URL}/conformance/body/form`, { field1: 'value1', field2: 'value2' });\n",
            );
        }
        self.maybe_clear_cookie_jar(script);
        script.push_str(
            "      check(res, { 'body:form-urlencoded': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // Multipart body
        script.push_str("    {\n");
        script.push_str(
            "      let data = { field: http.file('test content', 'test.txt', 'text/plain') };\n",
        );
        if self.config.has_custom_headers() {
            script.push_str(&format!(
                "      let res = http.post(`${{BASE_URL}}/conformance/body/multipart`, data, {{ headers: {} }});\n",
                self.config.custom_headers_js_object()
            ));
        } else {
            script.push_str(
                "      let res = http.post(`${BASE_URL}/conformance/body/multipart`, data);\n",
            );
        }
        self.maybe_clear_cookie_jar(script);
        script.push_str(
            "      check(res, { 'body:multipart': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        script.push_str("  });\n\n");
    }

    fn generate_schema_types_group(&self, script: &mut String) {
        script.push_str("  group('Schema Types', function () {\n");

        let types = [
            ("string", r#"{ "value": "hello" }"#, "schema:string"),
            ("integer", r#"{ "value": 42 }"#, "schema:integer"),
            ("number", r#"{ "value": 3.14 }"#, "schema:number"),
            ("boolean", r#"{ "value": true }"#, "schema:boolean"),
            ("array", r#"{ "value": [1, 2, 3] }"#, "schema:array"),
            ("object", r#"{ "value": { "nested": "data" } }"#, "schema:object"),
        ];

        for (type_name, body, check_name) in types {
            script.push_str("    {\n");
            let url = format!("${{BASE_URL}}/conformance/schema/{}", type_name);
            let body_str = format!("'{}'", body);
            self.emit_post_like(script, "post", &url, &body_str, "JSON_HEADERS");
            script.push_str(&format!(
                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
                check_name
            ));
            script.push_str("    }\n");
        }

        script.push_str("  });\n\n");
    }

    fn generate_composition_group(&self, script: &mut String) {
        script.push_str("  group('Composition', function () {\n");

        let compositions = [
            ("oneOf", r#"{ "type": "string", "value": "test" }"#, "composition:oneOf"),
            ("anyOf", r#"{ "value": "test" }"#, "composition:anyOf"),
            ("allOf", r#"{ "name": "test", "id": 1 }"#, "composition:allOf"),
        ];

        for (kind, body, check_name) in compositions {
            script.push_str("    {\n");
            let url = format!("${{BASE_URL}}/conformance/composition/{}", kind);
            let body_str = format!("'{}'", body);
            self.emit_post_like(script, "post", &url, &body_str, "JSON_HEADERS");
            script.push_str(&format!(
                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
                check_name
            ));
            script.push_str("    }\n");
        }

        script.push_str("  });\n\n");
    }

    fn generate_string_formats_group(&self, script: &mut String) {
        script.push_str("  group('String Formats', function () {\n");

        let formats = [
            ("date", r#"{ "value": "2024-01-15" }"#, "format:date"),
            ("date-time", r#"{ "value": "2024-01-15T10:30:00Z" }"#, "format:date-time"),
            ("email", r#"{ "value": "test@example.com" }"#, "format:email"),
            ("uuid", r#"{ "value": "550e8400-e29b-41d4-a716-446655440000" }"#, "format:uuid"),
            ("uri", r#"{ "value": "https://example.com/path" }"#, "format:uri"),
            ("ipv4", r#"{ "value": "192.168.1.1" }"#, "format:ipv4"),
            ("ipv6", r#"{ "value": "::1" }"#, "format:ipv6"),
        ];

        for (fmt, body, check_name) in formats {
            script.push_str("    {\n");
            let url = format!("${{BASE_URL}}/conformance/formats/{}", fmt);
            let body_str = format!("'{}'", body);
            self.emit_post_like(script, "post", &url, &body_str, "JSON_HEADERS");
            script.push_str(&format!(
                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
                check_name
            ));
            script.push_str("    }\n");
        }

        script.push_str("  });\n\n");
    }

    fn generate_constraints_group(&self, script: &mut String) {
        script.push_str("  group('Constraints', function () {\n");

        let constraints = [
            (
                "required",
                "JSON.stringify({ required_field: 'present' })",
                "constraint:required",
            ),
            ("optional", "JSON.stringify({})", "constraint:optional"),
            ("minmax", "JSON.stringify({ value: 50 })", "constraint:minmax"),
            ("pattern", "JSON.stringify({ value: 'ABC-123' })", "constraint:pattern"),
            ("enum", "JSON.stringify({ status: 'active' })", "constraint:enum"),
        ];

        for (kind, body, check_name) in constraints {
            script.push_str("    {\n");
            let url = format!("${{BASE_URL}}/conformance/constraints/{}", kind);
            self.emit_post_like(script, "post", &url, body, "JSON_HEADERS");
            script.push_str(&format!(
                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
                check_name
            ));
            script.push_str("    }\n");
        }

        script.push_str("  });\n\n");
    }

    fn generate_response_codes_group(&self, script: &mut String) {
        script.push_str("  group('Response Codes', function () {\n");

        let codes = [
            ("200", "response:200"),
            ("201", "response:201"),
            ("204", "response:204"),
            ("400", "response:400"),
            ("404", "response:404"),
        ];

        for (code, check_name) in codes {
            script.push_str("    {\n");
            let url = format!("${{BASE_URL}}/conformance/responses/{}", code);
            self.emit_get(script, &url, None);
            script.push_str(&format!(
                "      check(res, {{ '{}': (r) => r.status === {} }});\n",
                check_name, code
            ));
            script.push_str("    }\n");
        }

        script.push_str("  });\n\n");
    }

    fn generate_http_methods_group(&self, script: &mut String) {
        script.push_str("  group('HTTP Methods', function () {\n");

        // GET
        script.push_str("    {\n");
        self.emit_get(script, "${BASE_URL}/conformance/methods", None);
        script.push_str(
            "      check(res, { 'method:GET': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // POST
        script.push_str("    {\n");
        self.emit_post_like(
            script,
            "post",
            "${BASE_URL}/conformance/methods",
            "JSON.stringify({ action: 'create' })",
            "JSON_HEADERS",
        );
        script.push_str(
            "      check(res, { 'method:POST': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // PUT
        script.push_str("    {\n");
        self.emit_post_like(
            script,
            "put",
            "${BASE_URL}/conformance/methods",
            "JSON.stringify({ action: 'update' })",
            "JSON_HEADERS",
        );
        script.push_str(
            "      check(res, { 'method:PUT': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // PATCH
        script.push_str("    {\n");
        self.emit_post_like(
            script,
            "patch",
            "${BASE_URL}/conformance/methods",
            "JSON.stringify({ action: 'patch' })",
            "JSON_HEADERS",
        );
        script.push_str(
            "      check(res, { 'method:PATCH': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // DELETE
        script.push_str("    {\n");
        self.emit_no_body(script, "del", "${BASE_URL}/conformance/methods");
        script.push_str(
            "      check(res, { 'method:DELETE': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // HEAD
        script.push_str("    {\n");
        self.emit_no_body(script, "head", "${BASE_URL}/conformance/methods");
        script.push_str(
            "      check(res, { 'method:HEAD': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // OPTIONS
        script.push_str("    {\n");
        self.emit_no_body(script, "options", "${BASE_URL}/conformance/methods");
        script.push_str(
            "      check(res, { 'method:OPTIONS': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        script.push_str("  });\n\n");
    }

    fn generate_content_negotiation_group(&self, script: &mut String) {
        script.push_str("  group('Content Types', function () {\n");

        script.push_str("    {\n");
        self.emit_get(
            script,
            "${BASE_URL}/conformance/content-types",
            Some("{ 'Accept': 'application/json' }"),
        );
        script.push_str(
            "      check(res, { 'content:negotiation': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        script.push_str("  });\n\n");
    }

    fn generate_security_group(&self, script: &mut String) {
        script.push_str("  group('Security', function () {\n");

        // Bearer token
        script.push_str("    {\n");
        self.emit_get(
            script,
            "${BASE_URL}/conformance/security/bearer",
            Some("{ 'Authorization': 'Bearer test-token-123' }"),
        );
        script.push_str(
            "      check(res, { 'security:bearer': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // API Key
        let api_key = self.config.api_key.as_deref().unwrap_or("test-api-key-123");
        script.push_str("    {\n");
        let api_key_hdrs = format!("{{ 'X-API-Key': '{}' }}", api_key);
        self.emit_get(script, "${BASE_URL}/conformance/security/apikey", Some(&api_key_hdrs));
        script.push_str(
            "      check(res, { 'security:apikey': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        // Basic auth
        let basic_creds = self.config.basic_auth.as_deref().unwrap_or("user:pass");
        let encoded = base64_encode(basic_creds);
        script.push_str("    {\n");
        let basic_hdrs = format!("{{ 'Authorization': 'Basic {}' }}", encoded);
        self.emit_get(script, "${BASE_URL}/conformance/security/basic", Some(&basic_hdrs));
        script.push_str(
            "      check(res, { 'security:basic': (r) => r.status >= 200 && r.status < 500 });\n",
        );
        script.push_str("    }\n");

        script.push_str("  });\n\n");
    }

    fn generate_handle_summary(&self, script: &mut String) {
        // Determine the report output path. When output_dir is set, use an absolute
        // path so k6 writes the file where the CLI expects to find it regardless of CWD.
        let report_path = match &self.config.output_dir {
            Some(dir) => {
                let abs = std::fs::canonicalize(dir)
                    .unwrap_or_else(|_| dir.clone())
                    .join("conformance-report.json");
                abs.to_string_lossy().to_string()
            }
            None => "conformance-report.json".to_string(),
        };

        script.push_str("export function handleSummary(data) {\n");
        script.push_str("  // Extract check results for conformance reporting\n");
        script.push_str("  let checks = {};\n");
        script.push_str("  if (data.metrics && data.metrics.checks) {\n");
        script.push_str("    // Overall check pass rate\n");
        script.push_str("    checks.overall_pass_rate = data.metrics.checks.values.rate;\n");
        script.push_str("  }\n");
        script.push_str("  // Collect per-check results from root_group\n");
        script.push_str("  let checkResults = {};\n");
        script.push_str("  function walkGroups(group) {\n");
        script.push_str("    if (group.checks) {\n");
        script.push_str("      for (let checkObj of group.checks) {\n");
        script.push_str("        checkResults[checkObj.name] = {\n");
        script.push_str("          passes: checkObj.passes,\n");
        script.push_str("          fails: checkObj.fails,\n");
        script.push_str("        };\n");
        script.push_str("      }\n");
        script.push_str("    }\n");
        script.push_str("    if (group.groups) {\n");
        script.push_str("      for (let subGroup of group.groups) {\n");
        script.push_str("        walkGroups(subGroup);\n");
        script.push_str("      }\n");
        script.push_str("    }\n");
        script.push_str("  }\n");
        script.push_str("  if (data.root_group) {\n");
        script.push_str("    walkGroups(data.root_group);\n");
        script.push_str("  }\n");
        script.push_str("  let result = {\n");
        script.push_str(&format!(
            "    '{}': JSON.stringify({{ checks: checkResults, overall: checks }}, null, 2),\n",
            report_path
        ));
        script.push_str("    'summary.json': JSON.stringify(data),\n");
        script.push_str("    stdout: textSummary(data, { indent: '  ', enableColors: true }),\n");
        script.push_str("  };\n");
        script.push_str("  return result;\n");
        script.push_str("}\n\n");
        script.push_str("// textSummary fallback\n");
        script.push_str("function textSummary(data, opts) {\n");
        script.push_str("  return JSON.stringify(data, null, 2);\n");
        script.push_str("}\n");
    }
}

/// Simple base64 encoding for basic auth
fn base64_encode(input: &str) -> String {
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let bytes = input.as_bytes();
    let mut result = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
        let triple = (b0 << 16) | (b1 << 8) | b2;
        result.push(CHARS[((triple >> 18) & 0x3F) as usize] as char);
        result.push(CHARS[((triple >> 12) & 0x3F) as usize] as char);
        if chunk.len() > 1 {
            result.push(CHARS[((triple >> 6) & 0x3F) as usize] as char);
        } else {
            result.push('=');
        }
        if chunk.len() > 2 {
            result.push(CHARS[(triple & 0x3F) as usize] as char);
        } else {
            result.push('=');
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_conformance_script() {
        let config = ConformanceConfig {
            target_url: "http://localhost:8080".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: None,
            base_path: None,
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        let generator = ConformanceGenerator::new(config);
        let script = generator.generate().unwrap();

        assert!(script.contains("import http from 'k6/http'"));
        assert!(script.contains("vus: 1"));
        assert!(script.contains("iterations: 1"));
        assert!(script.contains("group('Parameters'"));
        assert!(script.contains("group('Request Bodies'"));
        assert!(script.contains("group('Schema Types'"));
        assert!(script.contains("group('Composition'"));
        assert!(script.contains("group('String Formats'"));
        assert!(script.contains("group('Constraints'"));
        assert!(script.contains("group('Response Codes'"));
        assert!(script.contains("group('HTTP Methods'"));
        assert!(script.contains("group('Content Types'"));
        assert!(script.contains("group('Security'"));
        assert!(script.contains("handleSummary"));
    }

    #[test]
    fn test_base64_encode() {
        assert_eq!(base64_encode("user:pass"), "dXNlcjpwYXNz");
        assert_eq!(base64_encode("a"), "YQ==");
        assert_eq!(base64_encode("ab"), "YWI=");
        assert_eq!(base64_encode("abc"), "YWJj");
    }

    #[test]
    fn test_conformance_script_with_custom_auth() {
        let config = ConformanceConfig {
            target_url: "https://api.example.com".to_string(),
            api_key: Some("my-api-key".to_string()),
            basic_auth: Some("admin:secret".to_string()),
            skip_tls_verify: true,
            categories: None,
            base_path: None,
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        let generator = ConformanceGenerator::new(config);
        let script = generator.generate().unwrap();

        assert!(script.contains("insecureSkipTLSVerify: true"));
        assert!(script.contains("my-api-key"));
        assert!(script.contains(&base64_encode("admin:secret")));
    }

    #[test]
    fn test_should_include_category_none_includes_all() {
        let config = ConformanceConfig {
            target_url: "http://localhost:8080".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: None,
            base_path: None,
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        assert!(config.should_include_category("Parameters"));
        assert!(config.should_include_category("Security"));
        assert!(config.should_include_category("Anything"));
    }

    #[test]
    fn test_should_include_category_filtered() {
        let config = ConformanceConfig {
            target_url: "http://localhost:8080".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: Some(vec!["Parameters".to_string(), "Security".to_string()]),
            base_path: None,
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        assert!(config.should_include_category("Parameters"));
        assert!(config.should_include_category("Security"));
        assert!(config.should_include_category("parameters")); // case-insensitive
        assert!(!config.should_include_category("Composition"));
        assert!(!config.should_include_category("Schema Types"));
    }

    #[test]
    fn test_generate_with_category_filter() {
        let config = ConformanceConfig {
            target_url: "http://localhost:8080".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: Some(vec!["Parameters".to_string(), "Security".to_string()]),
            base_path: None,
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        let generator = ConformanceGenerator::new(config);
        let script = generator.generate().unwrap();

        assert!(script.contains("group('Parameters'"));
        assert!(script.contains("group('Security'"));
        assert!(!script.contains("group('Request Bodies'"));
        assert!(!script.contains("group('Schema Types'"));
        assert!(!script.contains("group('Composition'"));
    }

    #[test]
    fn test_effective_base_url_no_base_path() {
        let config = ConformanceConfig {
            target_url: "https://example.com".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: None,
            base_path: None,
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        assert_eq!(config.effective_base_url(), "https://example.com");
    }

    #[test]
    fn test_effective_base_url_with_base_path() {
        let config = ConformanceConfig {
            target_url: "https://example.com".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: None,
            base_path: Some("/api".to_string()),
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        assert_eq!(config.effective_base_url(), "https://example.com/api");
    }

    #[test]
    fn test_effective_base_url_trailing_slash_normalization() {
        let config = ConformanceConfig {
            target_url: "https://example.com/".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: None,
            base_path: Some("/api".to_string()),
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        assert_eq!(config.effective_base_url(), "https://example.com/api");
    }

    #[test]
    fn test_effective_base_url_trailing_slash_no_base_path() {
        // Regression: --target https://192.168.2.86/ without --base-path
        // must not produce double slashes when combined with /path
        let config = ConformanceConfig {
            target_url: "https://192.168.2.86/".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: None,
            base_path: None,
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        assert_eq!(config.effective_base_url(), "https://192.168.2.86");
    }

    #[test]
    fn test_generate_script_with_base_path() {
        let config = ConformanceConfig {
            target_url: "https://192.168.2.86".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: true,
            categories: None,
            base_path: Some("/api".to_string()),
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        let generator = ConformanceGenerator::new(config);
        let script = generator.generate().unwrap();

        assert!(script.contains("const BASE_URL = 'https://192.168.2.86/api'"));
        // Verify URLs include the base path via BASE_URL
        assert!(script.contains("${BASE_URL}/conformance/"));
    }

    #[test]
    fn test_generate_with_custom_headers() {
        let config = ConformanceConfig {
            target_url: "https://192.168.2.86".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: true,
            categories: Some(vec!["Parameters".to_string()]),
            base_path: Some("/api".to_string()),
            custom_headers: vec![
                ("X-Avi-Tenant".to_string(), "admin".to_string()),
                ("X-CSRFToken".to_string(), "real-token".to_string()),
            ],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        let generator = ConformanceGenerator::new(config);
        let script = generator.generate().unwrap();

        // Custom headers should be inlined into requests (no separate const)
        assert!(
            !script.contains("const CUSTOM_HEADERS"),
            "Script should NOT declare a CUSTOM_HEADERS const"
        );
        assert!(script.contains("'X-Avi-Tenant': 'admin'"));
        assert!(script.contains("'X-CSRFToken': 'real-token'"));
    }

    #[test]
    fn test_custom_headers_js_object() {
        let config = ConformanceConfig {
            target_url: "http://localhost".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: None,
            base_path: None,
            custom_headers: vec![
                ("Authorization".to_string(), "Bearer abc123".to_string()),
                ("X-Custom".to_string(), "value".to_string()),
            ],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        let js = config.custom_headers_js_object();
        assert!(js.contains("'Authorization': 'Bearer abc123'"));
        assert!(js.contains("'X-Custom': 'value'"));
    }
}
