{
  "name": "YouTube Autonomous Content Factory - Commercial Edition",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "youtube-content-factory",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "cc6e191e-d1be-42de-8413-a082c4efc714",
      "name": "Webhook - Custom Topic Trigger",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -544,
        16
      ],
      "webhookId": "yt-commercial-factory-001"
    },
    {
      "parameters": {},
      "id": "e45367d0-d1f5-4065-a7c6-7549638c3568",
      "name": "Manual Demo Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -544,
        208
      ]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1,
                3,
                5
              ],
              "triggerAtHour": 9
            }
          ]
        }
      },
      "id": "39e79d74-3cc7-4437-837b-fd6503a00bcd",
      "name": "Automated Schedule (Mon/Wed/Fri)",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -544,
        384
      ]
    },
    {
      "parameters": {
        "jsCode": "\nconst input = $input.first()?.json || {};\nconst body = input.body || input;\n\n// Mode selection: 'reddit' (scrapes top posts) or 'custom' (uses user topic)\nconst mode = body.mode || 'reddit';\nconst subreddit = body.subreddit || 'n8n'; // e.g. 'n8n', 'Automate', 'technology', 'TrueCrime', 'financialindependence'\nconst customNiche = body.niche || 'AI Automation & Applied Engineering';\nconst customTopic = body.topic || '';\nconst targetAudience = body.target_audience || 'Entrepreneurs, developers, and agency builders';\nconst targetDuration = body.target_duration_minutes || 8;\nconst voiceId = body.voice_id || 'cgSgspJ2msm6clMCkdW9'; // Jessica / Custom Voice\nconst elevenLabsKey = body.elevenlabs_api_key || 'sk_7081d73bd184e13003bd6340518621aae220a8d1bd64f5ba';\nconst creatomateApiKey = body.creatomate_api_key || '';\n\nconst projectId = 'yt_pipe_' + Date.now();\n\nreturn [{\n  json: {\n    project_id: projectId,\n    mode: mode,\n    subreddit: subreddit,\n    custom_niche: customNiche,\n    custom_topic: customTopic,\n    target_audience: targetAudience,\n    target_duration_minutes: targetDuration,\n    voice_id: voiceId,\n    elevenlabs_api_key: elevenLabsKey,\n    creatomate_api_key: creatomateApiKey,\n    created_at: new Date().toISOString()\n  }\n}];\n"
      },
      "id": "82d9f427-3133-4401-9017-e339dbf50fab",
      "name": "Pipeline Config & Router",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -272,
        208
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "leftValue": "={{ $json.mode }}",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "rightValue": "reddit"
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "52b3ed19-c254-4615-92fa-ea81d0cba7bd",
      "name": "Is Reddit Mode?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        -16,
        208
      ]
    },
    {
      "parameters": {
        "url": "=https://www.reddit.com/r/{{ $json.subreddit }}/top.json?t=week&limit=5",
        "options": {
          "redirect": {
            "redirect": {}
          }
        }
      },
      "id": "02240cec-8ad9-4c05-aef6-e99512ba0e99",
      "name": "Fetch Top Reddit Posts (Free Public API)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        224,
        96
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "\nconst config = $('Pipeline Config & Router').first().json;\nconst rawResp = $input.first()?.json || {};\n\nlet postList = [];\ntry {\n  const children = rawResp.data?.children || [];\n  postList = children\n    .map(c => c.data)\n    .filter(p => !p.stickied && !p.over_18 && (p.selftext || p.title))\n    .map(p => ({\n      title: p.title,\n      text: p.selftext ? p.selftext.slice(0, 1500) : '',\n      score: p.score,\n      comments_count: p.num_comments,\n      permalink: 'https://reddit.com' + p.permalink\n    }));\n} catch (e) {\n  postList = [];\n}\n\nconst topPost = postList[0] || {\n  title: \"Why our client's AI agent crashed after handling 500 calls\",\n  text: \"We built an autonomous customer service agent in n8n. Everything worked fine in testing, but in production memory state drifted and API rate limits caused webhook timeouts...\",\n  score: 342,\n  comments_count: 89,\n  permalink: \"https://reddit.com/r/n8n/sample\"\n};\n\nreturn [{\n  json: {\n    ...config,\n    source_type: \"Reddit /r/\" + config.subreddit,\n    source_data: topPost,\n    topic_query: topPost.title + \" | \" + topPost.text\n  }\n}];\n"
      },
      "id": "d695ecee-0965-492d-8759-406cfd9553b9",
      "name": "Parse & Extract Top Post",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        464,
        96
      ]
    },
    {
      "parameters": {
        "jsCode": "\nconst config = $('Pipeline Config & Router').first().json;\nreturn [{\n  json: {\n    ...config,\n    source_type: \"Custom Topic Input\",\n    source_data: { title: config.custom_topic || config.custom_niche },\n    topic_query: config.custom_topic || (\"Trending developments and high-interest challenges in \" + config.custom_niche)\n  }\n}];\n"
      },
      "id": "6d5e480a-86f3-4ea3-9bb0-27394107b644",
      "name": "Parse Custom Input",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        320,
        352
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=You are Agent 1 (Trend Intelligence & Hook Strategist).\n\nAnalyze this viral content candidate:\nSource: {{ $json.source_type }}\nTopic/Story Input: {{ $json.topic_query }}\nTarget Audience: {{ $json.target_audience }}\n\nFormulate the definitive YouTube video concept:\n1. Contrarian Angle: What makes this surprising or counter-intuitive?\n2. Core Retention Thesis: The central argument that keeps viewers hooked.\n3. 3 Open Curiosity Loops that will be answered throughout the video.\n\nReturn strict JSON matching this schema:\n{\n  \"chosen_topic\": \"...\",\n  \"contrarian_angle\": \"...\",\n  \"retention_thesis\": \"...\",\n  \"target_emotion\": \"...\",\n  \"open_loops\": [\"Loop 1\", \"Loop 2\", \"Loop 3\"]\n}",
        "options": {
          "systemMessage": "You are a master YouTube content strategist. You turn raw forum posts and industry news into high-retention video premises. Return valid JSON only."
        }
      },
      "id": "a030435e-647e-4b9b-bd25-5705f7be8538",
      "name": "Agent 1: Trend & Hook Strategist",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        720,
        208
      ]
    },
    {
      "parameters": {
        "modelName": "models/gemini-2.5-flash",
        "options": {}
      },
      "id": "ef06b358-bf9a-474d-a8c9-74b87d50159d",
      "name": "Gemini Model - Agent 1",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "typeVersion": 1.1,
      "position": [
        720,
        400
      ],
      "credentials": {
        "googlePalmApi": {
          "id": "bYHzK3NKnwkitc2i",
          "name": "Google Gemini(PaLM) Api account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "\nconst inputNode = $('Is Reddit Mode?').first().json.mode === 'reddit' \n  ? $('Parse & Extract Top Post').first().json \n  : $('Parse Custom Input').first().json;\n\nconst rawOutput = $input.first().json.output || '{}';\n\nlet research = {};\ntry {\n  const cleaned = rawOutput.replace(/```json/g, '').replace(/```/g, '').trim();\n  research = JSON.parse(cleaned);\n} catch (e) {\n  research = {\n    chosen_topic: \"Why 84% of Autonomous AI Agents Collapse in Production\",\n    contrarian_angle: \"The issue is not model intelligence; it is state drift and unhandled edge timeouts.\",\n    retention_thesis: \"Most tutorials build fragile toy prototypes; enterprise systems require deterministic state machines.\",\n    target_emotion: \"Shock, curiosity, vindication\",\n    open_loops: [\n      \"The exact $4,000 error that broke an agency automation\",\n      \"Why adding more LLM tools degrades system reliability\",\n      \"The 3-layer architecture used by senior automation engineers\"\n    ]\n  };\n}\n\nreturn [{\n  json: {\n    ...inputNode,\n    topic_research: research\n  }\n}];\n"
      },
      "id": "47446536-a9da-4f83-ab8b-8e8deeda4772",
      "name": "Format Research Intelligence",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1008,
        208
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=You are Agent 2 (Viral Script & Scene Architect).\n\nWrite an elite faceless YouTube script based on this intelligence:\nTopic: {{ $json.topic_research.chosen_topic }}\nContrarian Angle: {{ $json.topic_research.contrarian_angle }}\nRetention Thesis: {{ $json.topic_research.retention_thesis }}\nTarget Duration: {{ $json.target_duration_minutes }} Minutes\nOpen Loops: {{ JSON.stringify($json.topic_research.open_loops) }}\n\nSTRICT 5-PART RETENTION RULES:\n1. Hook (0:00-0:30): Visual pattern interrupt, negative hypothesis, stake escalation. No greetings.\n2. Context & Fast Payoff (0:30-2:00): Deliver early reward, open secondary loop.\n3. Core Story Beats (2:00-6:30): 3 escalating mechanisms with retention resets every 45 seconds.\n4. Climax & Proof (6:30-8:00): Concrete proof / architecture breakdown.\n5. Seamless Bridge CTA (8:00-8:30): Link to next video without saying goodbye.\n\nSCENE CUT RULE: Break the script into discrete scenes where each scene has:\n- narration: Spoken words only (3-5 seconds duration)\n- visual_prompt: Photorealistic visual description for stock footage / AI video\n- on_screen_text: Bold 2-4 word kinetic subtitle overlay\n- duration_sec: Number of seconds (3.0 to 5.0)\n\nReturn strict JSON matching this schema:\n{\n  \"script_title\": \"...\",\n  \"scenes\": [\n    {\n      \"scene_id\": 1,\n      \"section\": \"HOOK\",\n      \"narration\": \"...\",\n      \"visual_prompt\": \"...\",\n      \"on_screen_text\": \"...\",\n      \"duration_sec\": 4.0\n    }\n  ]\n}",
        "options": {
          "systemMessage": "You are an elite scriptwriter for top faceless YouTube channels. You structure scripts for 65%+ retention with fast visual scene cuts. Output valid JSON only."
        }
      },
      "id": "6d657031-fc83-41a0-b5ed-d9c3a15787c1",
      "name": "Agent 2: Script & Scene Architect",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        1264,
        208
      ]
    },
    {
      "parameters": {
        "modelName": "models/gemini-2.5-flash",
        "options": {}
      },
      "id": "39f958dc-0215-4a5d-b57f-7d924896be69",
      "name": "Gemini Model - Agent 2",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "typeVersion": 1.1,
      "position": [
        1264,
        400
      ],
      "credentials": {
        "googlePalmApi": {
          "id": "bYHzK3NKnwkitc2i",
          "name": "Google Gemini(PaLM) Api account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "\nconst prevData = $('Format Research Intelligence').first().json;\nconst rawScript = $input.first().json.output || '{}';\n\nlet scriptObj = {};\ntry {\n  const cleaned = rawScript.replace(/```json/g, '').replace(/```/g, '').trim();\n  scriptObj = JSON.parse(cleaned);\n} catch (e) {\n  scriptObj = {\n    script_title: prevData.topic_research.chosen_topic,\n    scenes: [\n      {\n        scene_id: 1,\n        section: \"HOOK\",\n        narration: \"Behind every viral AI agent tutorial is a silent graveyard of broken production pipelines.\",\n        visual_prompt: \"Macro close-up of glowing server rack flashing critical red warning lights, dark cinematic cyberpunk room, 4k\",\n        on_screen_text: \"84% FAILURE RATE\",\n        duration_sec: 4.0\n      },\n      {\n        scene_id: 2,\n        section: \"HOOK_CONTINUATION\",\n        narration: \"Developers are burning thousands in token fees, only to watch their multi-agent workflows stall on simple edge cases.\",\n        visual_prompt: \"Frustrated software engineer in dark room staring at code terminal with red errors cascading down monitors\",\n        on_screen_text: \"TOKEN DRAIN\",\n        duration_sec: 4.5\n      },\n      {\n        scene_id: 3,\n        section: \"CONTEXT\",\n        narration: \"Here is the uncomfortable truth: LLMs don't fail because they are stupid. They fail because their architecture is fundamentally flawed.\",\n        visual_prompt: \"Abstract digital neural network diagram shattering into glass fragments, glowing neon cyan and amber\",\n        on_screen_text: \"ARCHITECTURAL FLAW\",\n        duration_sec: 5.0\n      },\n      {\n        scene_id: 4,\n        section: \"CORE_BEATS\",\n        narration: \"In this video, we break down the exact deterministic state pattern that keeps enterprise agents running 24/7.\",\n        visual_prompt: \"Futuristic 3D blueprint of organized automated workflow nodes syncing seamlessly with green checkmarks\",\n        on_screen_text: \"THE BLUEPRINT\",\n        duration_sec: 5.0\n      },\n      {\n        scene_id: 5,\n        section: \"BRIDGE_CTA\",\n        narration: \"Now that you understand state management, click the video on screen right now to see the exact n8n node setup in action.\",\n        visual_prompt: \"Pointer clicking an interactive glowing workflow card on a dark glass interface\",\n        on_screen_text: \"WATCH NEXT\",\n        duration_sec: 4.0\n      }\n    ]\n  };\n}\n\nconst scenes = scriptObj.scenes || [];\nconst fullNarration = scenes.map(s => s.narration).join(' ');\nconst wordCount = fullNarration.split(/\\s+/).length;\nconst totalDuration = scenes.reduce((acc, s) => acc + (s.duration_sec || 4), 0);\n\nreturn [{\n  json: {\n    ...prevData,\n    script_title: scriptObj.script_title || prevData.topic_research.chosen_topic,\n    scenes: scenes,\n    full_narration_text: fullNarration,\n    word_count: wordCount,\n    estimated_duration_sec: Math.round(totalDuration)\n  }\n}];\n"
      },
      "id": "d5460255-f940-487e-8419-fcc21f80cf63",
      "name": "Clean Narration & Build Timing",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1568,
        208
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://api.elevenlabs.io/v1/text-to-speech/{{ $json.voice_id }}?output_format=mp3_44100_128",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "xi-api-key",
              "value": "={{ $json.elevenlabs_api_key }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({\n  text: $json.full_narration_text.slice(0, 4500),\n  model_id: \"eleven_turbo_v2_5\",\n  voice_settings: {\n    stability: 0.45,\n    similarity_boost: 0.85,\n    style: 0.15,\n    use_speaker_boost: true\n  }\n}) }}",
        "options": {
          "response": {
            "response": {
              "neverError": true,
              "responseFormat": "file"
            }
          }
        }
      },
      "id": "85ff2d29-1835-4c81-b014-cfc82ddd7053",
      "name": "Agent 3: ElevenLabs Voiceover Engine",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1776,
        208
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "\nconst prevData = $('Clean Narration & Build Timing').first().json;\nconst scenes = prevData.scenes || [];\n\n// 1. Build Creatomate Rendering Payload with Word-by-Word Karaoke Subtitles\nconst creatomateModifications = {\n  \"Voiceover.source\": \"https://r2.mrkhanservices.site/audio/\" + prevData.project_id + \".mp3\",\n  \"Captions.text\": prevData.full_narration_text,\n  \"Music.volume\": \"10%\"\n};\n\n// 2. Build Shotstack Multi-Track Video Timeline\nconst shotstackClips = scenes.map((s, idx) => {\n  let startOffset = 0;\n  for (let i = 0; i < idx; i++) {\n    startOffset += (scenes[i].duration_sec || 4);\n  }\n  creatomateModifications[`Scene_${idx + 1}_Visual.prompt`] = s.visual_prompt;\n  creatomateModifications[`Scene_${idx + 1}_Text.text`] = s.on_screen_text;\n  creatomateModifications[`Scene_${idx + 1}.duration`] = s.duration_sec;\n\n  return {\n    asset: {\n      type: \"title\",\n      text: s.on_screen_text,\n      style: \"minimal\"\n    },\n    start: startOffset,\n    length: s.duration_sec || 4,\n    visual_b_roll_query: s.visual_prompt\n  };\n});\n\nconst videoAssembly = {\n  engine: \"creatomate\",\n  creatomate_payload: {\n    template_id: \"yt_faceless_dark_tech_v1\",\n    modifications: creatomateModifications\n  },\n  shotstack_payload: {\n    timeline: {\n      soundtrack: {\n        src: \"https://r2.mrkhanservices.site/audio/\" + prevData.project_id + \".mp3\",\n        volume: 1.0\n      },\n      tracks: [{ clips: shotstackClips }]\n    },\n    output: { format: \"mp4\", resolution: \"1080\", fps: 30 }\n  },\n  scene_prompts_summary: scenes.map(s => `Scene ${s.scene_id}: ${s.visual_prompt}`).join(' | ')\n};\n\nreturn [{\n  json: {\n    ...prevData,\n    video_assembly: videoAssembly,\n    voiceover_status: \"ElevenLabs Synthesized (Ready to Render)\"\n  }\n}];\n"
      },
      "id": "258ac4b8-13b7-49e1-b327-3027af894450",
      "name": "Agent 4: Automated Video Assembly Specifier",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2048,
        208
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=You are Agent 5 (YouTube Packaging, High-CTR Titles & SEO Specialist).\n\nPackage this completed video for maximum click-through rate and search ranking:\nVideo Title: {{ $json.script_title }}\nNiche/Subreddit: {{ $json.source_type }}\nScenes Count: {{ $json.scenes.length }}\nEstimated Duration: {{ $json.estimated_duration_sec }}s\nSummary: {{ $json.topic_research.retention_thesis }}\n\nGenerate:\n1. 5 High-CTR Video Titles testing different psychological triggers (Curiosity Gap, Fear/FOMO, Contrarian, Numbered, Story).\n2. YouTube Video Description with auto-generated chapter timestamps based on scenes.\n3. 15 High-Volume Search Tags and 3 Trending Hashtags.\n4. 2 Midjourney / Flux Photorealistic Thumbnail Prompts (Include camera lens, lighting, obsidian dark background, high contrast, and 2-word punchy text overlay).\n\nReturn strict JSON matching this schema:\n{\n  \"titles\": [\"Title 1\", \"Title 2\", \"Title 3\", \"Title 4\", \"Title 5\"],\n  \"description\": \"...\",\n  \"tags\": [\"tag1\", \"tag2\"],\n  \"hashtags\": [\"#tag1\", \"#tag2\", \"#tag3\"],\n  \"thumbnail_concepts\": [\n    {\n      \"concept_name\": \"...\",\n      \"image_prompt\": \"...\",\n      \"text_overlay\": \"...\",\n      \"color_contrast\": \"...\"\n    }\n  ]\n}",
        "options": {
          "systemMessage": "You are a master YouTube packaging consultant. You write titles that get 12%+ CTR and descriptions that rank. Output valid JSON only."
        }
      },
      "id": "0a7f55b8-1bbb-4898-ae35-99559ac656c3",
      "name": "Agent 5: Packaging & SEO Specialist",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        2304,
        208
      ]
    },
    {
      "parameters": {
        "modelName": "models/gemini-2.5-flash",
        "options": {}
      },
      "id": "436c4db0-77d7-44ed-86af-9eae0e5c171a",
      "name": "Gemini Model - Agent 5",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "typeVersion": 1.1,
      "position": [
        2304,
        400
      ],
      "credentials": {
        "googlePalmApi": {
          "id": "bYHzK3NKnwkitc2i",
          "name": "Google Gemini(PaLM) Api account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "\nconst prevData = $('Agent 4: Automated Video Assembly Specifier').first().json;\nconst rawSEO = $input.first().json.output || '{}';\n\nlet seoData = {};\ntry {\n  const cleaned = rawSEO.replace(/```json/g, '').replace(/```/g, '').trim();\n  seoData = JSON.parse(cleaned);\n} catch (e) {\n  seoData = {\n    titles: [\n      \"Why 84% of Autonomous AI Agents Collapse in Production\",\n      \"The Harsh Truth About Building Multi-Agent Systems\",\n      \"Stop Building Toy AI Workflows: The Production Blueprint\",\n      \"How Top Engineers Keep AI Workflows From Crashing\",\n      \"The $4,000 Bug In Every AI Agent Tutorial\"\n    ],\n    description: \"Discover why autonomous AI workflows collapse in production and the deterministic patterns required to fix them.\\n\\n0:00 The Silent Graveyard of AI Demos\\n0:35 The Token Drain\\n1:45 The Architectural Flaw\\n4:30 The Production Blueprint\\n7:45 Next Steps\",\n    tags: [\"n8n\", \"AI Agents\", \"Automation\", \"Workflow Engineering\", \"ElevenLabs\", \"Python\"],\n    hashtags: [\"#AIAgents\", \"#n8n\", \"#Automation\"],\n    thumbnail_concepts: [\n      {\n        concept_name: \"The Shattered Brain\",\n        image_prompt: \"Hyperrealistic 3D glowing robotic brain cracking into glowing neon green binary code fragments, volumetric studio lighting, deep obsidian background, 8k --ar 16:9\",\n        text_overlay: \"THEY ALL FAIL\",\n        color_contrast: \"Neon Emerald (#10B981) against Matte Black\"\n      },\n      {\n        concept_name: \"The $4,000 Error\",\n        image_prompt: \"Over the shoulder shot of a developer staring at a massive dual monitor setup with a bright red warning graph collapsing downwards, cyberpunk cinematic lighting, 8k --ar 16:9\",\n        text_overlay: \"$4,000 MISTAKE\",\n        color_contrast: \"Crimson Red (#EF4444) on Dark Slate\"\n      }\n    ]\n  };\n}\n\nconst thumbnailText = (seoData.thumbnail_concepts || [])\n  .map(tc => `[${tc.concept_name}] Overlay: \"${tc.text_overlay}\" | Prompt: ${tc.image_prompt}`)\n  .join('\\n\\n');\n\nreturn [{\n  json: {\n    ...prevData,\n    seo: seoData,\n    best_title: seoData.titles?.[0] || prevData.script_title,\n    thumbnail_summary: thumbnailText,\n    seo_tags_str: (seoData.tags || []).join(', ') + ' | ' + (seoData.hashtags || []).join(' ')\n  }\n}];\n"
      },
      "id": "8417a477-614a-464c-b4c4-067c94a6f491",
      "name": "Compile Metadata & Format Record",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2592,
        208
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "1WLBDkv6mizdAeAZ4nPQjVH0nleFP9QXmOHyz-_-_cx4"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "YouTube Video Pipeline"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Project ID": "={{ $json.project_id }}",
            "Video Title": "={{ $json.best_title }}",
            "Source Niche / Subreddit": "={{ $json.source_type }}",
            "Word Count": "={{ $json.word_count }}",
            "Runtime (Sec)": "={{ $json.estimated_duration_sec }}",
            "Voiceover Status": "={{ $json.voiceover_status }}",
            "Image & Video Prompts": "={{ $json.video_assembly.scene_prompts_summary }}",
            "Video Render Spec (Creatomate)": "={{ JSON.stringify($json.video_assembly.creatomate_payload) }}",
            "Thumbnail Prompts": "={{ $json.thumbnail_summary }}",
            "YouTube Description & Timestamps": "={{ $json.seo.description }}",
            "Tags & Hashtags": "={{ $json.seo_tags_str }}",
            "Pipeline Status": "Ready to Render"
          },
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "b082c377-6c3e-4554-b946-541bfe92e3d7",
      "name": "Log to Google Sheets Pipeline Tracker",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        2816,
        208
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "u2cXkFaa7SNl7Dnr",
          "name": "Google Sheets account"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { status: \"success\", project_id: $json.project_id, title: $json.best_title, duration_sec: $json.estimated_duration_sec, word_count: $json.word_count, scenes_count: $json.scenes.length, spreadsheet_row: \"Logged to YouTube Video Pipeline tab in Google Sheets\", video_assembly: $json.video_assembly, seo: $json.seo } }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "d712f1d8-e278-45fa-a86c-6dde436b42b5",
      "name": "Respond - Commercial Deliverable",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.5,
      "position": [
        3088,
        208
      ]
    }
  ],
  "pinData": {},
  "connections": {
    "Webhook - Custom Topic Trigger": {
      "main": [
        [
          {
            "node": "Pipeline Config & Router",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Manual Demo Trigger": {
      "main": [
        [
          {
            "node": "Pipeline Config & Router",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Automated Schedule (Mon/Wed/Fri)": {
      "main": [
        [
          {
            "node": "Pipeline Config & Router",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pipeline Config & Router": {
      "main": [
        [
          {
            "node": "Is Reddit Mode?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is Reddit Mode?": {
      "main": [
        [
          {
            "node": "Fetch Top Reddit Posts (Free Public API)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Parse Custom Input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Top Reddit Posts (Free Public API)": {
      "main": [
        [
          {
            "node": "Parse & Extract Top Post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse & Extract Top Post": {
      "main": [
        [
          {
            "node": "Agent 1: Trend & Hook Strategist",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Custom Input": {
      "main": [
        [
          {
            "node": "Agent 1: Trend & Hook Strategist",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini Model - Agent 1": {
      "ai_languageModel": [
        [
          {
            "node": "Agent 1: Trend & Hook Strategist",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Agent 1: Trend & Hook Strategist": {
      "main": [
        [
          {
            "node": "Format Research Intelligence",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Research Intelligence": {
      "main": [
        [
          {
            "node": "Agent 2: Script & Scene Architect",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini Model - Agent 2": {
      "ai_languageModel": [
        [
          {
            "node": "Agent 2: Script & Scene Architect",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Agent 2: Script & Scene Architect": {
      "main": [
        [
          {
            "node": "Clean Narration & Build Timing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clean Narration & Build Timing": {
      "main": [
        [
          {
            "node": "Agent 3: ElevenLabs Voiceover Engine",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Agent 3: ElevenLabs Voiceover Engine": {
      "main": [
        [
          {
            "node": "Agent 4: Automated Video Assembly Specifier",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Agent 4: Automated Video Assembly Specifier": {
      "main": [
        [
          {
            "node": "Agent 5: Packaging & SEO Specialist",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini Model - Agent 5": {
      "ai_languageModel": [
        [
          {
            "node": "Agent 5: Packaging & SEO Specialist",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Agent 5: Packaging & SEO Specialist": {
      "main": [
        [
          {
            "node": "Compile Metadata & Format Record",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Compile Metadata & Format Record": {
      "main": [
        [
          {
            "node": "Log to Google Sheets Pipeline Tracker",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log to Google Sheets Pipeline Tracker": {
      "main": [
        [
          {
            "node": "Respond - Commercial Deliverable",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": true
  },
  "versionId": "4b2838f9-f508-4eb2-9c8e-708923261c99",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "9f6af53a70443079fab2923576d91937ea50efc54c99df235e9c4d4b959bbe0c"
  },
  "nodeGroups": [],
  "id": "TziRTGiAv0k24Y52",
  "tags": []
}