{
  "name": "Fill missing Wix SEO titles and meta descriptions with Gemini",
  "nodes": [
    {
      "id": "sticky0",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -608,
        -160
      ],
      "parameters": {
        "width": 480,
        "height": 1104,
        "content": "## Fill missing Wix SEO titles and meta descriptions with Gemini\n\nWix writes a title like \"Page Name | My Site\" for every page, product and blog post,\nand leaves the meta description empty. Google then invents its own snippet.\n\nThis workflow finds every item with no real SEO tags, writes a title and meta\ndescription from the page's own content, and saves them back. It fills gaps only, so\nanything you wrote by hand stays untouched.\n\n### How it works\n\n1. Reads the SEO tags on your pages, blog posts and store products.\n2. Keeps only the items Wix reports as having no custom tags, so no AI quota is spent finding them.\n3. Pulls real product copy, options and prices for product pages.\n4. Sends the batch to Gemini once, using a strict JSON schema.\n5. Checks every suggestion for length, duplicates, emoji and shouting.\n6. Saves the survivors, then reports what changed and what was rejected.\n\n### Setup steps\n\n- [ ] Create a Wix API key with View SEO Settings, Manage SEO Settings and Read Products\n- [ ] Add it as Header Auth named `Authorization` on the three Wix HTTP nodes\n- [ ] Add your Gemini key as Header Auth named `x-goog-api-key` on the Gemini node only\n- [ ] Paste your Wix site ID into Set Wix Configuration\n- [ ] Run once with `dry_run` true, read the report, then set it to false\n\n### Customization\n\nSet Wix Configuration holds the item types, batch size and character limits. To change\nthe tone of the copy, edit the numbered rules in Create Gemini API Request.\n\n**Note:** page and blog tags save to the site draft, so publish in the Wix editor to\ntake them live. Store products go live straight away."
      },
      "typeVersion": 1
    },
    {
      "id": "sticky1",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -48,
        -160
      ],
      "parameters": {
        "color": 7,
        "width": 400,
        "height": 320,
        "content": "## Schedule and settings\n\nRuns weekly, then sets the Wix site, item types, brand name, batch size, character limits and dry-run mode that every later step reads."
      },
      "typeVersion": 1
    },
    {
      "id": "sticky2",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        432,
        -160
      ],
      "parameters": {
        "color": 7,
        "width": 592,
        "height": 320,
        "content": "## Read the SEO tags from Wix\n\nExpands the configured item types into one row each, fetches the current SEO tags per type, and turns a bad response into a readable error instead of a silent failure."
      },
      "typeVersion": 1
    },
    {
      "id": "sticky3",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1072,
        -160
      ],
      "parameters": {
        "color": 7,
        "width": 592,
        "height": 496,
        "content": "## Find the gaps\n\nKeeps items Wix reports as having no custom tags, skipping anything noindex or already written by hand. Wix does this filtering, so no AI quota is spent finding them. When nothing needs doing, the run explains why instead of returning an empty result."
      },
      "typeVersion": 1
    },
    {
      "id": "sticky4",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1712,
        -160
      ],
      "parameters": {
        "color": 7,
        "width": 592,
        "height": 320,
        "content": "## Add the product copy\n\nPulls real descriptions, info sections, options and price range from the Wix Stores catalog so product pages get specific copy instead of a guess from the page name."
      },
      "typeVersion": 1
    },
    {
      "id": "sticky5",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2400,
        -160
      ],
      "parameters": {
        "color": 7,
        "width": 592,
        "height": 320,
        "content": "## Write and check the copy\n\nOne Gemini call covers the whole batch. Every suggestion is then checked for length, duplicates, emoji and shouting, and anything that fails is dropped with a reason."
      },
      "typeVersion": 1
    },
    {
      "id": "sticky6",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3072,
        -128
      ],
      "parameters": {
        "color": 7,
        "width": 832,
        "height": 480,
        "content": "## Save back to Wix\n\nDry run stops here and reports. Otherwise each item is patched individually and the real HTTP status of every write is reported, because the Wix bulk endpoint returns successes it never performed."
      },
      "typeVersion": 1
    },
    {
      "id": "trg",
      "name": "When Monday at 9am",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 9,
              "triggerAtMinute": 0
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "cfg",
      "name": "Set Wix Configuration",
      "type": "n8n-nodes-base.set",
      "position": [
        200,
        0
      ],
      "parameters": {
        "mode": "manual",
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "a1",
              "name": "wix_site_id",
              "type": "string",
              "value": "PASTE_YOUR_WIX_SITE_ID_HERE"
            },
            {
              "id": "a2",
              "name": "item_types",
              "type": "string",
              "value": "STATIC_PAGE,BLOG_POST,STORES_PRODUCT"
            },
            {
              "id": "a3",
              "name": "brand_name",
              "type": "string",
              "value": "Your Brand"
            },
            {
              "id": "a4",
              "name": "dry_run",
              "type": "boolean",
              "value": true
            },
            {
              "id": "a5",
              "name": "max_items_per_run",
              "type": "number",
              "value": 20
            },
            {
              "id": "a6",
              "name": "title_max_chars",
              "type": "number",
              "value": 60
            },
            {
              "id": "a7",
              "name": "desc_min_chars",
              "type": "number",
              "value": 120
            },
            {
              "id": "a8",
              "name": "desc_max_chars",
              "type": "number",
              "value": 158
            },
            {
              "id": "a9",
              "name": "gemini_model",
              "type": "string",
              "value": "gemini-3.6-flash"
            },
            {
              "id": "a10",
              "name": "skip_noindex",
              "type": "boolean",
              "value": true
            },
            {
              "id": "a11",
              "name": "publish_drafted_types",
              "type": "boolean",
              "value": false
            }
          ]
        },
        "includeOtherFields": false
      },
      "typeVersion": 3.4
    },
    {
      "id": "typ",
      "name": "Parse Item Types",
      "type": "n8n-nodes-base.code",
      "position": [
        480,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\nconst cfg = $input.first().json;\nreturn String(cfg.item_types || '')\n  .split(',').map(s => s.trim().toUpperCase()).filter(Boolean)\n  .map(t => ({ json: { itemType: t } }));\n"
      },
      "typeVersion": 2
    },
    {
      "id": "get",
      "name": "Get Wix SEO Tags",
      "type": "n8n-nodes-base.httpRequest",
      "maxTries": 3,
      "position": [
        680,
        0
      ],
      "parameters": {
        "url": "=https://www.wixapis.com/seo-metatags-server/v1/item-seo-tags/{{ $json.itemType }}",
        "options": {
          "response": {
            "response": {
              "neverError": true,
              "fullResponse": true
            }
          }
        },
        "sendHeaders": true,
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "headerParameters": {
          "parameters": [
            {
              "name": "wix-site-id",
              "value": "={{ $('Set Wix Configuration').first().json.wix_site_id }}"
            }
          ]
        }
      },
      "retryOnFail": true,
      "typeVersion": 4.2,
      "waitBetweenTries": 3000
    },
    {
      "id": "chk",
      "name": "Validate Wix SEO Response",
      "type": "n8n-nodes-base.code",
      "position": [
        880,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\nconst rows = $input.all();\nconst types = $('Parse Item Types').all().map(i => i.json.itemType);\nconst out = [];\nfor (let i = 0; i < rows.length; i++) {\n  const r = rows[i].json || {};\n  const status = r.statusCode;\n  const body = r.body || {};\n  const itemType = types[i] || 'UNKNOWN';\n  if (status === 401 || status === 403) {\n    throw new Error('Wix rejected the API key (HTTP ' + status + '). Check the key is valid, that it has View SEO Settings and Manage SEO Settings permissions, and that wix_site_id matches a site the key can reach.');\n  }\n  if (status === 428) {\n    throw new Error('This site runs a different Wix Stores catalog version than the endpoint expects. Wix says: ' + JSON.stringify(body).slice(0, 200));\n  }\n  if (status !== 200) {\n    throw new Error('Wix returned HTTP ' + status + ' for ' + itemType + ': ' + JSON.stringify(body).slice(0, 300));\n  }\n  out.push({ json: Object.assign({ __itemType: itemType }, body) });\n}\nreturn out;\n"
      },
      "typeVersion": 2
    },
    {
      "id": "gap",
      "name": "Identify Missing Tags",
      "type": "n8n-nodes-base.code",
      "position": [
        1120,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\nconst cfg = $('Set Wix Configuration').first().json;\nconst brand = String(cfg.brand_name || '').trim();\nconst maxItems = Number(cfg.max_items_per_run) || 20;\nconst skipNoindex = cfg.skip_noindex !== false && cfg.skip_noindex !== 'false';\n\nconst pick = (tags, fn) => (tags || []).map(t => t.tag).find(fn);\nconst out = [];\nconst skipped = { noindex: 0, alreadyWritten: 0, nothingMissing: 0 };\nlet scanned = 0;\n\nfor (const item of $input.all()) {\n  const j = item.json;\n  const itemType = j.__itemType;\n  for (const rec of (j.itemSeoTags || [])) {\n    scanned++;\n    const rt = rec.resolvedTags || [];\n    const titleTag = pick(rt, t => t.type === 'title');\n    const descTag  = pick(rt, t => t.type === 'meta' && t.props && t.props.name === 'description');\n    const ogDesc   = pick(rt, t => t.type === 'meta' && t.props && t.props.property === 'og:description');\n    const canon    = pick(rt, t => t.type === 'link' && t.props && t.props.rel === 'canonical');\n    const robots   = pick(rt, t => t.type === 'meta' && t.props && t.props.name === 'robots');\n\n    const currentTitle = titleTag ? String(titleTag.children || '') : '';\n    const currentDesc  = descTag && descTag.props ? String(descTag.props.content || '') : '';\n    const ogText       = ogDesc && ogDesc.props ? String(ogDesc.props.content || '') : '';\n    const url          = canon && canon.props ? String(canon.props.href || '') : '';\n    const noindex      = robots && robots.props ? String(robots.props.content || '').includes('noindex') : false;\n\n    // Pages Wix is told not to index are not worth spending AI quota on.\n    if (noindex && skipNoindex) { skipped.noindex++; continue; }\n    // Somebody already wrote these by hand. Leave their work alone.\n    if (rec.hasOverride && currentDesc) { skipped.alreadyWritten++; continue; }\n\n    const needsDesc  = !currentDesc;\n    const needsTitle = !rec.hasOverride;\n    if (!needsDesc && !needsTitle) { skipped.nothingMissing++; continue; }\n\n    const slug = url ? String(url.split('?')[0].replace(/\\/$/, '').split('/').pop() || '') : '';\n\n    out.push({ json: {\n      itemId: rec.itemId,\n      itemType,\n      url,\n      slug: slug.replace(/[-_]+/g, ' '),\n      currentTitle,\n      currentDesc,\n      sourceText: ogText,\n      brand,\n      needsTitle,\n      needsDesc,\n      // Carried so the write step can merge instead of overwrite.\n      existingTags: rec.tags || []\n    }});\n  }\n}\n\nif (out.length === 0) return [{ json: { __none: true, scanned, skipped, skipNoindex } }];\nif (out.length <= maxItems) return out;\n\n// Take a fair share of each item type. A site with 200 static pages would otherwise\n// use the whole batch on pages and never reach the products.\nconst buckets = {};\nfor (const o of out) (buckets[o.json.itemType] = buckets[o.json.itemType] || []).push(o);\nconst keys = Object.keys(buckets);\nconst picked = [];\nlet round = 0;\nwhile (picked.length < maxItems) {\n  let tookOne = false;\n  for (const k of keys) {\n    if (buckets[k][round]) {\n      picked.push(buckets[k][round]);\n      tookOne = true;\n      if (picked.length >= maxItems) break;\n    }\n  }\n  if (!tookOne) break;\n  round++;\n}\nreturn picked;\n"
      },
      "typeVersion": 2,
      "alwaysOutputData": true
    },
    {
      "id": "any",
      "name": "If Tags Missing",
      "type": "n8n-nodes-base.if",
      "position": [
        1312,
        0
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "c1",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              },
              "leftValue": "={{ $json.itemId }}"
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "non",
      "name": "Log Unchanged Status",
      "type": "n8n-nodes-base.code",
      "position": [
        1520,
        176
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\nconst cfg = $('Set Wix Configuration').first().json;\nconst j = $input.first().json || {};\nconst s = j.skipped || {};\nconst notes = [];\nif (s.noindex)        notes.push(s.noindex + ' item(s) are set to noindex, so they were skipped. A site that has never been published is entirely noindex. Set skip_noindex to false in Settings if you want to prepare tags before launch.');\nif (s.alreadyWritten) notes.push(s.alreadyWritten + ' item(s) already have a custom title and description. This workflow never overwrites work somebody did by hand.');\nif (s.nothingMissing) notes.push(s.nothingMissing + ' item(s) already had everything they needed.');\nif (!notes.length)    notes.push('No items of the selected types were found. Check item_types in Settings, and that the API key can reach this site.');\nreturn [{ json: {\n  mode: 'No changes needed',\n  site_id: cfg.wix_site_id,\n  itemsScanned: j.scanned || 0,\n  proposed: 0,\n  written: 0,\n  whyNothingHappened: notes\n}}];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "pp",
      "name": "Prepare Product ID Lookup",
      "type": "n8n-nodes-base.code",
      "position": [
        1760,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\n// One lookup for every product in this batch. Costs nothing when there are none.\nconst ids = $input.all().map(i => i.json.itemId).filter(Boolean);\nconst productIds = $input.all().filter(i => i.json.itemType === 'STORES_PRODUCT').map(i => i.json.itemId);\nreturn [{ json: {\n  search: {\n    filter: productIds.length ? { id: { $in: productIds } } : { id: { $in: ['+1234567890+1234567890'] } },\n    cursorPaging: { limit: 100 }\n  },\n  fields: ['DESCRIPTION', 'INFO_SECTION']\n}}];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "pf",
      "name": "Post Product Search",
      "type": "n8n-nodes-base.httpRequest",
      "onError": "continueRegularOutput",
      "position": [
        1960,
        0
      ],
      "parameters": {
        "url": "https://www.wixapis.com/stores/v3/products/search",
        "method": "POST",
        "options": {
          "response": {
            "response": {
              "neverError": true,
              "fullResponse": true
            }
          }
        },
        "jsonBody": "={{ JSON.stringify($json) }}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "headerParameters": {
          "parameters": [
            {
              "name": "wix-site-id",
              "value": "={{ $('Set Wix Configuration').first().json.wix_site_id }}"
            }
          ]
        }
      },
      "typeVersion": 4.2,
      "alwaysOutputData": true
    },
    {
      "id": "pm",
      "name": "Combine Product Data",
      "type": "n8n-nodes-base.code",
      "position": [
        2160,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\n// Wix returns product copy as Ricos rich content. Flatten it to plain text.\nconst flat = (n) => {\n  if (!n) return '';\n  if (Array.isArray(n)) return n.map(flat).join(' ');\n  if (typeof n === 'object') {\n    if (n.textData && n.textData.text) return n.textData.text;\n    return n.nodes ? flat(n.nodes) : '';\n  }\n  return '';\n};\n\nconst res = $input.first().json || {};\nconst products = {};\nif (res.statusCode === 200 && res.body && Array.isArray(res.body.products)) {\n  for (const p of res.body.products) {\n    const bits = [];\n    const desc = flat((p.description || {}).nodes).trim();\n    if (desc) bits.push(desc);\n    for (const s of (p.infoSections || [])) {\n      const t = flat((s.description || {}).nodes).trim();\n      if (t) bits.push(s.title + ': ' + t);\n    }\n    const opts = (p.options || []).map(o => {\n      const choices = ((o.choicesSettings || {}).choices || []).map(c => c.name).filter(Boolean);\n      return choices.length ? o.name + ' (' + choices.join(', ') + ')' : o.name;\n    }).filter(Boolean);\n    if (opts.length) bits.push('Options: ' + opts.join('; '));\n    const price = p.actualPriceRange && p.actualPriceRange.minValue ? p.actualPriceRange.minValue.formattedAmount : null;\n    if (price) bits.push('Price from ' + price);\n    products[p.id] = { name: p.name, text: bits.join('. ') };\n  }\n}\n\nreturn $('Identify Missing Tags').all().map(row => {\n  const j = Object.assign({}, row.json);\n  const p = products[j.itemId];\n  if (p) {\n    j.productName = p.name;\n    j.sourceText = [j.sourceText, p.text].filter(Boolean).join('. ');\n  }\n  return { json: j };\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "prm",
      "name": "Create Gemini API Request",
      "type": "n8n-nodes-base.code",
      "position": [
        2440,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\nconst cfg = $('Set Wix Configuration').first().json;\nconst items = $input.all().map(i => i.json);\nconst brand = String(cfg.brand_name || '').trim();\nconst titleMax = Number(cfg.title_max_chars) || 60;\nconst descMin = Number(cfg.desc_min_chars) || 120;\nconst descMax = Number(cfg.desc_max_chars) || 158;\n\nconst label = { STATIC_PAGE: 'website page', BLOG_POST: 'blog post', STORES_PRODUCT: 'product page' };\n\nconst lines = items.map((it, n) => {\n  const bits = [];\n  bits.push('itemId: ' + it.itemId);\n  bits.push('this is a ' + (label[it.itemType] || it.itemType.toLowerCase()));\n  if (it.productName) bits.push('product name: ' + it.productName);\n  if (it.slug) bits.push('page slug: ' + it.slug);\n  if (it.currentTitle) bits.push('current title tag: ' + it.currentTitle);\n  if (it.sourceText) bits.push('page content: ' + String(it.sourceText).slice(0, 900));\n  if (it.url) bits.push('url: ' + it.url);\n  return '### Item ' + (n + 1) + '\\n' + bits.join('\\n');\n}).join('\\n\\n');\n\nconst prompt = [\n  'Write SEO title tags and meta descriptions for pages on a website' +\n    (brand ? ' called \"' + brand + '\"' : '') + '.',\n  '',\n  'Rules:',\n  '1. Title: at most ' + titleMax + ' characters INCLUDING any brand suffix. Lead with what the page is about, not the brand.',\n  '2. Meta description: between ' + descMin + ' and ' + descMax + ' characters. Plain sentences that say what the visitor gets.',\n  '3. Use only the information given. Never invent prices, shipping times, discounts, guarantees, locations, awards, review scores or stock levels.',\n  '4. No clickbait, no ALL CAPS, no exclamation marks, no emoji, no quote marks wrapping the line.',\n  '5. Every title and every description must differ from every other one in this batch.',\n  '6. If the current title tag is already specific and useful, return it unchanged and focus on the description.',\n  '7. Write in the same language as the source material.',\n  '8. Return one object per item, reusing the exact itemId given.',\n  '',\n  'Items:',\n  '',\n  lines\n].join('\\n');\n\nreturn [{ json: {\n  contents: [{ role: 'user', parts: [{ text: prompt }] }],\n  generationConfig: {\n    temperature: 0.4,\n    responseMimeType: 'application/json',\n    responseSchema: {\n      type: 'ARRAY',\n      items: {\n        type: 'OBJECT',\n        properties: {\n          itemId: { type: 'STRING' },\n          title: { type: 'STRING' },\n          metaDescription: { type: 'STRING' }\n        },\n        required: ['itemId', 'title', 'metaDescription']\n      }\n    }\n  }\n}}];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "gem",
      "name": "Post to Gemini API",
      "type": "n8n-nodes-base.httpRequest",
      "maxTries": 5,
      "position": [
        2640,
        0
      ],
      "parameters": {
        "url": "=https://generativelanguage.googleapis.com/v1beta/models/{{ $('Set Wix Configuration').first().json.gemini_model }}:generateContent",
        "method": "POST",
        "options": {},
        "jsonBody": "={{ JSON.stringify($json) }}",
        "sendBody": true,
        "specifyBody": "json",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth"
      },
      "retryOnFail": true,
      "typeVersion": 4.2,
      "waitBetweenTries": 5000
    },
    {
      "id": "val",
      "name": "Validate Generated Tags",
      "type": "n8n-nodes-base.code",
      "position": [
        2840,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\nconst cfg = $('Set Wix Configuration').first().json;\nconst titleMax = Number(cfg.title_max_chars) || 60;\nconst descMin = Number(cfg.desc_min_chars) || 120;\nconst descMax = Number(cfg.desc_max_chars) || 158;\n\nconst gaps = {};\nfor (const g of $('Combine Product Data').all()) gaps[g.json.itemId] = g.json;\n\nconst raw = $input.first().json;\nlet parsed;\ntry { parsed = JSON.parse(raw.candidates[0].content.parts[0].text); }\ncatch (e) { throw new Error('Gemini did not return usable JSON. Response started: ' + JSON.stringify(raw).slice(0, 300)); }\nif (!Array.isArray(parsed)) throw new Error('Expected a JSON array from Gemini, got ' + typeof parsed);\n\nconst clean = s => String(s == null ? '' : s).replace(/\\s+/g, ' ').replace(/^[\"']|[\"']$/g, '').trim();\nconst seenTitles = new Set();\nconst seenDescs = new Set();\nconst accepted = [];\nconst rejected = [];\n\nfor (const row of parsed) {\n  const gap = gaps[row.itemId];\n  if (!gap) { rejected.push({ itemId: row.itemId, reason: 'returned an itemId that was not in this batch' }); continue; }\n\n  const title = clean(row.title);\n  const desc = clean(row.metaDescription);\n  const curTitle = clean(gap.currentTitle);\n  const curDesc = clean(gap.currentDesc);\n  const why = [];\n\n  if (!title) why.push('empty title');\n  if (title.length > titleMax) why.push('title ' + title.length + ' chars, limit ' + titleMax);\n  if (!desc) why.push('empty description');\n  if (desc && desc.length < descMin) why.push('description ' + desc.length + ' chars, minimum ' + descMin);\n  if (desc.length > descMax) why.push('description ' + desc.length + ' chars, maximum ' + descMax);\n  if (/[!]|[\\u{1F300}-\\u{1FAFF}]/u.test(title + ' ' + desc)) why.push('contains an exclamation mark or emoji');\n  if (title && title === title.toUpperCase() && title.length > 8) why.push('title is all caps');\n  if (title && seenTitles.has(title.toLowerCase())) why.push('duplicate title within this batch');\n  if (desc && seenDescs.has(desc.toLowerCase())) why.push('duplicate description within this batch');\n\n  const titleChanged = title.toLowerCase() !== curTitle.toLowerCase();\n  const descChanged  = desc.toLowerCase() !== curDesc.toLowerCase();\n  if (!titleChanged && !descChanged) why.push('identical to what is already on the item, nothing to write');\n\n  if (why.length) { rejected.push({ itemId: row.itemId, url: gap.url, title, desc, reason: why.join('; ') }); continue; }\n\n  seenTitles.add(title.toLowerCase());\n  seenDescs.add(desc.toLowerCase());\n  accepted.push({\n    itemId: row.itemId,\n    itemType: gap.itemType,\n    url: gap.url,\n    beforeTitle: curTitle || '(none)',\n    beforeDesc: curDesc || '(none)',\n    title,\n    metaDescription: desc,\n    titleChanged,\n    descriptionAdded: !curDesc,\n    titleLen: title.length,\n    descLen: desc.length,\n    existingTags: gap.existingTags || []\n  });\n}\n\nreturn [{ json: { accepted, rejected, acceptedCount: accepted.length, rejectedCount: rejected.length } }];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "dry",
      "name": "Check Dry Run Status",
      "type": "n8n-nodes-base.if",
      "position": [
        3120,
        0
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "d1",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              },
              "leftValue": "={{ $('Set Wix Configuration').first().json.dry_run }}"
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "blk",
      "name": "Construct Write Requests",
      "type": "n8n-nodes-base.code",
      "position": [
        3320,
        176
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\nconst cfg = $('Set Wix Configuration').first().json;\nconst accepted = $input.first().json.accepted || [];\nconst publishDrafted = cfg.publish_drafted_types === true || cfg.publish_drafted_types === 'true';\nconst BASE = 'https://www.wixapis.com/seo-metatags-server/v1/item-seo-tags/';\n\n// Static pages and blog posts keep a draft and a published revision. Writing with\n// publish:true targets the published revision, while the draft is what the editor and\n// the read API show you, so the default is to write the draft.\nconst DRAFTED = ['STATIC_PAGE', 'BLOG_POST'];\n\n// A write replaces the item's ENTIRE tag set. Anything already there that we are not\n// changing (robots noindex on a cart page, a canonical override, custom og tags) has to\n// be carried across or it is destroyed silently.\nconst mergeTags = (existing, title, desc) => {\n  const keep = (existing || []).filter(t => {\n    if (t.type === 'title') return false;\n    if (t.type === 'meta' && t.props && t.props.name === 'description') return false;\n    return true;\n  });\n  return keep.concat([\n    { type: 'title', children: title },\n    { type: 'meta', props: { name: 'description', content: desc }, children: '' }\n  ]);\n};\n\n// One request per item. The bulk endpoint reports success for store products and then\n// writes nothing, so every type goes through the single-item endpoint instead.\nreturn accepted.map(r => {\n  const body = {\n    itemSeoTags: { tags: mergeTags(r.existingTags, r.title, r.metaDescription) },\n    fieldMask: 'tags'\n  };\n  if (DRAFTED.includes(r.itemType)) {\n    if (publishDrafted) body.publish = true;\n  } else {\n    body.publish = true;\n  }\n  return { json: {\n    url: BASE + r.itemType + '/' + r.itemId,\n    body,\n    itemId: r.itemId,\n    itemType: r.itemType,\n    title: r.title\n  }};\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "put",
      "name": "Patch Tags on Wix",
      "type": "n8n-nodes-base.httpRequest",
      "maxTries": 3,
      "position": [
        3520,
        176
      ],
      "parameters": {
        "url": "={{ $json.url }}",
        "method": "PATCH",
        "options": {
          "response": {
            "response": {
              "neverError": true,
              "fullResponse": true
            }
          }
        },
        "jsonBody": "={{ JSON.stringify($json.body) }}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "headerParameters": {
          "parameters": [
            {
              "name": "wix-site-id",
              "value": "={{ $('Set Wix Configuration').first().json.wix_site_id }}"
            }
          ]
        }
      },
      "retryOnFail": true,
      "typeVersion": 4.2,
      "waitBetweenTries": 3000
    },
    {
      "id": "rep",
      "name": "Log Changes Reported",
      "type": "n8n-nodes-base.code",
      "position": [
        3760,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\nconst cfg = $('Set Wix Configuration').first().json;\nconst v = $('Validate Generated Tags').first().json;\nconst dryRun = cfg.dry_run === true || cfg.dry_run === 'true';\n\nlet written = 0, failed = 0;\nconst apiErrors = [];\nif (!dryRun) {\n  const reqs = $('Construct Write Requests').all().map(i => i.json);\n  const rows = $input.all();\n  for (let i = 0; i < rows.length; i++) {\n    const r = rows[i].json || {};\n    const req = reqs[i] || {};\n    if (r.statusCode === 200) { written++; }\n    else {\n      failed++;\n      apiErrors.push({ itemId: req.itemId, itemType: req.itemType, status: r.statusCode,\n        description: JSON.stringify(r.body || {}).slice(0, 200) });\n    }\n  }\n}\n\nconst notes = [];\nif (dryRun) notes.push('Dry run. Nothing was sent to Wix. Set dry_run to false in Settings when the proposed tags look right.');\nif (!dryRun && written) notes.push('Static page and blog post tags are written to the site draft. Publish the site in the Wix editor for them to go live.');\nif (v.rejectedCount) notes.push(v.rejectedCount + ' suggestion(s) failed validation and were not written. See rejected below.');\n\nreturn [{ json: {\n  mode: dryRun ? 'DRY RUN - nothing written to Wix' : 'LIVE - tags written to Wix',\n  site_id: cfg.wix_site_id,\n  proposed: v.acceptedCount,\n  written: dryRun ? 0 : written,\n  writeFailures: dryRun ? 0 : failed,\n  rejectedByValidator: v.rejectedCount,\n  notes,\n  changes: v.accepted,\n  rejected: v.rejected,\n  apiErrors\n}}];\n"
      },
      "typeVersion": 2,
      "alwaysOutputData": true
    }
  ],
  "settings": {
    "executionOrder": "v1"
  },
  "connections": {
    "If Tags Missing": {
      "main": [
        [
          {
            "node": "Prepare Product ID Lookup",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Log Unchanged Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Wix SEO Tags": {
      "main": [
        [
          {
            "node": "Validate Wix SEO Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Item Types": {
      "main": [
        [
          {
            "node": "Get Wix SEO Tags",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Patch Tags on Wix": {
      "main": [
        [
          {
            "node": "Log Changes Reported",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Post to Gemini API": {
      "main": [
        [
          {
            "node": "Validate Generated Tags",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When Monday at 9am": {
      "main": [
        [
          {
            "node": "Set Wix Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Post Product Search": {
      "main": [
        [
          {
            "node": "Combine Product Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Dry Run Status": {
      "main": [
        [
          {
            "node": "Log Changes Reported",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Construct Write Requests",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Combine Product Data": {
      "main": [
        [
          {
            "node": "Create Gemini API Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Identify Missing Tags": {
      "main": [
        [
          {
            "node": "If Tags Missing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Wix Configuration": {
      "main": [
        [
          {
            "node": "Parse Item Types",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate Generated Tags": {
      "main": [
        [
          {
            "node": "Check Dry Run Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Construct Write Requests": {
      "main": [
        [
          {
            "node": "Patch Tags on Wix",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Gemini API Request": {
      "main": [
        [
          {
            "node": "Post to Gemini API",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Product ID Lookup": {
      "main": [
        [
          {
            "node": "Post Product Search",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate Wix SEO Response": {
      "main": [
        [
          {
            "node": "Identify Missing Tags",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
