Skip to content

The script, in full

This is the file your dashboard fills with an account token. Schedule it hourly. It sends a new search-term report every Monday in the account's time zone, and adds the negatives you approved: account-wide terms on a shared list named JunkTerms, and campaign-only terms on that campaign. If you already pasted an older copy, paste this one again. Google Ads does not fetch updates.
  • Schedule it hourly. The first run on Monday, in the account's time zone, sends that week's search terms. If Monday is missed, the next run catches up, once that week.

  • The first install is a dry run. It reads and posts, and it does not write negatives until JUNKTERMS_DRY_RUN is false.

  • It does not change bids, budgets, ads, or existing keywords.

junkterms.gs · Public preview, token removed
/**
 * JunkTerms
 * The first free analysis reads the last 90 days, up to the free cap.
 * Later runs read the last 7 days, up to the plan cap.
 * Posts those search terms to JunkTerms.
 * Account negatives go on a shared list named JunkTerms.
 * Campaign negatives are added only on that campaign.
 * Does not change bids, budgets, ads, or existing keywords.
 *
 * Schedule: hourly (Google Ads > Tools > Bulk actions > Scripts).
 * Search-term analysis is sent every Monday, in this account's time zone,
 * on the first hourly run that day. If Monday is missed (the account was
 * paused, or the script was installed mid-week), the next hourly run sends
 * that week's analysis. At most one analysis per Monday-to-Monday week.
 * Approved negatives are applied on the hourly runs.
 *
 * GAQL search_term_view is the current replacement for
 * SEARCH_QUERY_PERFORMANCE_REPORT (Search and Shopping).
 * Performance Max search terms come from campaign_search_term_view,
 * per campaign, without ad groups. Scripts cannot attach the shared list
 * to Performance Max, so approved negatives go on PMax campaigns as
 * campaign negative keywords through AdsApp.mutateAll. Preview and dry-run
 * only log what would be added.
 * Reference: https://developers.google.com/google-ads/scripts/docs/reference/adsapp/adsapp
 */
var JUNKTERMS_ENDPOINT = 'https://junkterms.com';
var JUNKTERMS_TOKEN = 'YOUR_ACCOUNT_TOKEN';
var SHARED_LIST_NAME = 'JunkTerms';
// First install only reads and posts. Set this to false after a Preview run looks right.
var JUNKTERMS_DRY_RUN = true;
// Reports go out every Monday in the account time zone. The gap below is a
// fallback, used only if the time zone cannot be read (server does the same).
var ANALYSIS_INTERVAL_MS = 6 * 24 * 60 * 60 * 1000;
var SEARCH_TERM_LIMIT = 5000;
var KEYWORD_LIMIT = 2000;

function main() {
  if (typeof AdsManagerApp !== 'undefined') {
    var iterator = AdsManagerApp.accounts().withLimit(50).get();
    var count = 0;
    while (iterator.hasNext()) {
      var account = iterator.next();
      AdsManagerApp.select(account);
      count++;
      try {
        runForCurrentAccount();
      } catch (err) {
        Logger.log('JunkTerms failed for ' + account.getCustomerId() + ': ' + err);
      }
    }
    if (count === 0) {
      Logger.log('JunkTerms: this manager account has no client accounts.');
    }
    return;
  }
  runForCurrentAccount();
}

function isDryRun() {
  try {
    var flag = PropertiesService.getScriptProperties().getProperty('JUNKTERMS_DRY_RUN');
    if (flag === 'false') return false;
    if (flag === 'true') return true;
  } catch (err) {
    Logger.log('JunkTerms could not read the dry-run flag: ' + err);
  }
  return JUNKTERMS_DRY_RUN !== false;
}

// Google Ads Preview never writes. The script also skips its own writes and the
// ack, so Preview cannot mark a negative applied that was never added.
function isPreview() {
  try {
    return AdsApp.getExecutionInfo().isPreview() === true;
  } catch (err) {
    return false;
  }
}

function runForCurrentAccount() {
  var account = AdsApp.currentAccount();
  var customerId = account.getCustomerId();
  var zone = accountTimeZone();
  var dryRun = isDryRun();
  var preview = isPreview();
  Logger.log('JunkTerms running for ' + customerId + (dryRun ? ' (DRY-RUN, no negatives will be written)' : preview ? ' (PREVIEW, no negatives will be written)' : ''));

  var pending = apiGet(pendingPath(customerId, zone));
  if (pending && pending.paused) {
    Logger.log(pending.reason === 'plan_limit'
      ? 'JunkTerms: this plan has no room for another account.'
      : 'Free analysis sent; subscribe to analyse new terms.');
    return;
  } else if (dryRun || preview) {
    var waiting = pending && pending.negatives ? pending.negatives.length : 0;
    if (dryRun) {
      Logger.log('JunkTerms DRY-RUN: would apply ' + waiting + ' negatives. Nothing was written. Set JUNKTERMS_DRY_RUN to false after Preview looks right.');
    } else {
      Logger.log('JunkTerms PREVIEW: would apply ' + waiting + ' negatives. Nothing was written and nothing is marked applied.');
    }
    previewPmaxNegatives(pending && pending.negatives ? pending.negatives : [], customerId);
  } else if (pending && pending.negatives && pending.negatives.length) {
    applyNegatives(pending.negatives, customerId);
  } else {
    // Nothing new to apply: still give a Performance Max campaign the script
    // has not seen before the account negatives already on the JunkTerms list.
    runPmaxNegatives(buildPmaxPlan([], customerId, null));
  }

  var plan = pending && pending.analysis ? pending.analysis : {};
  if (plan.due) {
    clearAnalyzed();
  } else if (!shouldAnalyze()) {
    Logger.log('JunkTerms: this week\'s analysis already sent. Applied approvals only.');
    return;
  }

  var dateRange = plan.dateRange === 'LAST_90_DAYS' || plan.dateRange === 'LAST_30_DAYS' || plan.dateRange === 'LAST_7_DAYS'
    ? plan.dateRange
    : 'LAST_7_DAYS';
  var termLimit = Number(plan.termLimit || SEARCH_TERM_LIMIT);
  if (!(termLimit > 0)) {
    Logger.log('JunkTerms: the term limit for this period is already used.');
    return;
  }

  var context = collectCampaignContext();
  var payload = {
    customerId: customerId,
    accountName: account.getName(),
    currency: account.getCurrencyCode(),
    timeZone: zone,
    searchTerms: fetchSearchTerms(dateRange, termLimit),
    activeKeywords: context.keywords,
    campaigns: context.campaigns
  };

  var result = apiPost('https://junkterms.com/api/script/ingest', payload);
  if (result && result.paused) {
    Logger.log('Free analysis sent; subscribe to analyse new terms.');
    return;
  }
  if (result && result.budgetStopped) {
    clearAnalyzed();
    Logger.log('JunkTerms classified with rules only because the model was unavailable. This was not counted. Run Preview again.');
    return;
  }
  markAnalyzed();
  var classified = result && result.classified != null ? result.classified : payload.searchTerms.length;
  var cached = result && result.cached ? result.cached : 0;
  Logger.log('JunkTerms classified ' + classified + ' of ' + payload.searchTerms.length + ' search terms.' + (cached ? ' ' + cached + ' were already classified.' : ''));
  if (result && result.free) {
    Logger.log('Free analysis sent; subscribe to analyse new terms.');
  }
}

function accountTimeZone() {
  try {
    return String(AdsApp.currentAccount().getTimeZone() || '');
  } catch (err) {
    Logger.log('JunkTerms could not read the account time zone: ' + err);
    return '';
  }
}

function pendingPath(customerId, zone) {
  var path = 'https://junkterms.com/api/script/pending?customerId=' + encodeURIComponent(customerId);
  if (zone) path += '&timeZone=' + encodeURIComponent(zone);
  return path;
}

// Same Monday rule as lib/analysis-schedule.ts. A missing time zone falls
// back to the 6-day gap so a run can still send an analysis.
function shouldAnalyze() {
  try {
    var props = PropertiesService.getScriptProperties();
    var last = Number(props.getProperty('JUNKTERMS_LAST_ANALYSIS_MS') || '0');
    if (!(last > 0)) return true;
    var zone = accountTimeZone();
    if (!zone) return (Date.now() - last) >= ANALYSIS_INTERVAL_MS;
    var weekStart = startOfAccountWeek(Date.now(), zone);
    if (!(weekStart > 0)) return (Date.now() - last) >= ANALYSIS_INTERVAL_MS;
    return last < weekStart;
  } catch (err) {
    Logger.log('JunkTerms could not read script properties: ' + err);
    return true;
  }
}

function startOfAccountWeek(nowMs, zone) {
  var ymd = Utilities.formatDate(new Date(nowMs), zone, 'yyyy-MM-dd');
  var monday = shiftIso(ymd, -daysSinceMonday(ymd));
  return zonedMidnightMs(monday, zone);
}

function daysSinceMonday(ymd) {
  var parts = ymd.split('-');
  var day = new Date(Date.UTC(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]))).getUTCDay();
  return day === 0 ? 6 : day - 1;
}

function zonedMidnightMs(iso, zone) {
  var parts = iso.split('-');
  var utcGuess = Date.UTC(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
  var offset = zoneOffsetMs(utcGuess, zone);
  var adjusted = utcGuess - offset;
  var offset2 = zoneOffsetMs(adjusted, zone);
  if (offset2 !== offset) adjusted = utcGuess - offset2;
  return adjusted;
}

function zoneOffsetMs(utcMs, zone) {
  var formatted = Utilities.formatDate(new Date(utcMs), zone, 'yyyy-MM-dd HH:mm:ss');
  var bits = formatted.split(/[- :]/);
  var hour = Number(bits[3]);
  if (hour === 24) hour = 0;
  var asUtc = Date.UTC(Number(bits[0]), Number(bits[1]) - 1, Number(bits[2]), hour, Number(bits[4]), Number(bits[5]));
  return asUtc - utcMs;
}

function markAnalyzed() {
  try {
    PropertiesService.getScriptProperties().setProperty('JUNKTERMS_LAST_ANALYSIS_MS', String(Date.now()));
  } catch (err) {
    Logger.log('JunkTerms could not store last analysis time: ' + err);
  }
}

function clearAnalyzed() {
  try {
    PropertiesService.getScriptProperties().deleteProperty('JUNKTERMS_LAST_ANALYSIS_MS');
  } catch (err) {
    Logger.log('JunkTerms could not clear the last analysis time: ' + err);
  }
}

function dateFilter(dateRange) {
  if (dateRange === 'LAST_90_DAYS') {
    var zone = AdsApp.currentAccount().getTimeZone();
    var today = Utilities.formatDate(new Date(), zone, 'yyyy-MM-dd');
    // DURING LAST_N_DAYS excludes today. BETWEEN is the 90 days ending yesterday.
    return "segments.date BETWEEN '" + shiftIso(today, -90) + "' AND '" + shiftIso(today, -1) + "'";
  }
  var range = dateRange === 'LAST_30_DAYS' ? 'LAST_30_DAYS' : 'LAST_7_DAYS';
  return 'segments.date DURING ' + range;
}

function shiftIso(iso, days) {
  var parts = iso.split('-');
  var utc = Date.UTC(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
  return Utilities.formatDate(new Date(utc + days * 24 * 60 * 60 * 1000), 'UTC', 'yyyy-MM-dd');
}

function fetchSearchTerms(dateRange, termLimit) {
  var limit = termLimit > 0 ? termLimit : SEARCH_TERM_LIMIT;
  var terms = fetchSearchViewTerms(dateRange, limit);
  var pmax = fetchPmaxSearchTerms(dateRange, limit);
  if (!pmax.length) return terms;
  var merged = terms.concat(pmax);
  merged.sort(function (a, b) {
    return (b.cost - a.cost) || (b.clicks - a.clicks) || (b.impressions - a.impressions);
  });
  return merged.slice(0, limit);
}

// Search and Shopping campaigns, with the ad group.
function fetchSearchViewTerms(dateRange, limit) {
  var query = [
    'SELECT',
    'search_term_view.search_term,',
    'campaign.id,',
    'campaign.name,',
    'campaign.advertising_channel_type,',
    'ad_group.name,',
    'metrics.clicks,',
    'metrics.impressions,',
    'metrics.cost_micros,',
    'metrics.conversions',
    'FROM search_term_view',
    'WHERE ' + dateFilter(dateRange),
    'AND metrics.impressions > 0',
    'ORDER BY metrics.cost_micros DESC, metrics.clicks DESC, metrics.impressions DESC',
    'LIMIT ' + limit
  ].join(' ');

  var terms = [];
  var rows = AdsApp.search(query);
  while (rows.hasNext()) {
    var row = rows.next();
    terms.push({
      term: String(readField(row, ['searchTermView', 'searchTerm'], 'search_term_view.search_term') || ''),
      campaign: String(readField(row, ['campaign', 'name'], 'campaign.name') || ''),
      campaignId: String(readField(row, ['campaign', 'id'], 'campaign.id') || ''),
      campaignType: String(readField(row, ['campaign', 'advertisingChannelType'], 'campaign.advertising_channel_type') || ''),
      adGroup: String(readField(row, ['adGroup', 'name'], 'ad_group.name') || ''),
      clicks: metricNumber(readField(row, ['metrics', 'clicks'], 'metrics.clicks')),
      impressions: metricNumber(readField(row, ['metrics', 'impressions'], 'metrics.impressions')),
      cost: metricNumber(readField(row, ['metrics', 'costMicros'], 'metrics.cost_micros')) / 1000000,
      conversions: metricNumber(readField(row, ['metrics', 'conversions'], 'metrics.conversions'))
    });
  }
  return terms;
}

// Performance Max search terms. search_term_view leaves PMax out;
// campaign_search_term_view (Google Ads API v21+) includes it, aggregated per
// campaign. PMax has no ad groups, and keyword segments drop PMax rows, so
// neither is selected. If the view is not available the Search terms still go out.
// Reference: https://developers.google.com/google-ads/api/fields/latest/campaign_search_term_view
function fetchPmaxSearchTerms(dateRange, limit) {
  var query = [
    'SELECT',
    'campaign_search_term_view.search_term,',
    'campaign.id,',
    'campaign.name,',
    'metrics.clicks,',
    'metrics.impressions,',
    'metrics.cost_micros,',
    'metrics.conversions',
    'FROM campaign_search_term_view',
    "WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'",
    'AND ' + dateFilter(dateRange),
    'AND metrics.impressions > 0',
    'ORDER BY metrics.cost_micros DESC, metrics.clicks DESC, metrics.impressions DESC',
    'LIMIT ' + limit
  ].join(' ');

  var terms = [];
  try {
    var rows = AdsApp.search(query);
    while (rows.hasNext()) {
      var row = rows.next();
      var term = String(readField(row, ['campaignSearchTermView', 'searchTerm'], 'campaign_search_term_view.search_term') || '');
      if (!term) continue;
      terms.push({
        term: term,
        campaign: String(readField(row, ['campaign', 'name'], 'campaign.name') || ''),
        campaignId: String(readField(row, ['campaign', 'id'], 'campaign.id') || ''),
        campaignType: 'PMAX',
        adGroup: '',
        clicks: metricNumber(readField(row, ['metrics', 'clicks'], 'metrics.clicks')),
        impressions: metricNumber(readField(row, ['metrics', 'impressions'], 'metrics.impressions')),
        cost: metricNumber(readField(row, ['metrics', 'costMicros'], 'metrics.cost_micros')) / 1000000,
        conversions: metricNumber(readField(row, ['metrics', 'conversions'], 'metrics.conversions'))
      });
    }
  } catch (err) {
    Logger.log('JunkTerms could not read Performance Max search terms; sending Search terms only: ' + err);
    return [];
  }
  if (terms.length) Logger.log('JunkTerms read ' + terms.length + ' Performance Max search terms.');
  return terms;
}

function metricNumber(value) {
  var n = Number(value);
  return isFinite(n) && n > 0 ? n : 0;
}

function readField(row, path, flatKey) {
  var current = row;
  for (var i = 0; i < path.length; i++) {
    if (current == null) break;
    current = current[path[i]];
  }
  if (current != null && typeof current !== 'object') return current;
  if (row && flatKey && row[flatKey] != null) return row[flatKey];
  return current == null ? '' : current;
}

function fetchActiveKeywords() {
  var out = [];
  var iter = AdsApp.keywords()
    .withCondition('Status = ENABLED')
    .withCondition('CampaignStatus = ENABLED')
    .withCondition('AdGroupStatus = ENABLED')
    .withLimit(KEYWORD_LIMIT)
    .get();
  while (iter.hasNext()) {
    var keyword = iter.next();
    try {
      var campaign = keyword.getCampaign();
      out.push({
        text: keyword.getText(),
        matchType: String(keyword.getMatchType()),
        campaign: campaign.getName(),
        campaignId: String(campaign.getId()),
        adGroup: keyword.getAdGroup().getName()
      });
    } catch (err) {
      Logger.log('JunkTerms skipped a keyword: ' + err);
    }
  }
  return out;
}

function collectCampaignContext() {
  var byName = {};
  function touch(id, name, channel) {
    var key = String(name || '');
    if (!key) return null;
    if (!byName[key]) {
      byName[key] = { id: String(id || ''), name: key, channel: String(channel || ''), adGroups: [], keywords: [] };
    }
    if (id && !byName[key].id) byName[key].id = String(id);
    if (channel && !byName[key].channel) byName[key].channel = String(channel);
    return byName[key];
  }
  function rememberGroup(profile, adGroup) {
    if (!profile || !adGroup) return;
    if (profile.adGroups.length >= 30) return;
    for (var i = 0; i < profile.adGroups.length; i++) {
      if (profile.adGroups[i] === adGroup) return;
    }
    profile.adGroups.push(adGroup);
  }
  var campaignIter = AdsApp.campaigns().withCondition('Status = ENABLED').withLimit(200).get();
  while (campaignIter.hasNext()) {
    var campaign = campaignIter.next();
    var channel = '';
    try {
      channel = String(campaign.getAdvertisingChannelType());
    } catch (err) {
      channel = '';
    }
    touch(campaign.getId(), campaign.getName(), channel);
  }
  if (typeof AdsApp.performanceMaxCampaigns === 'function') {
    try {
      var pmax = AdsApp.performanceMaxCampaigns().withCondition('Status = ENABLED').withLimit(100).get();
      while (pmax.hasNext()) {
        var pmaxCampaign = pmax.next();
        touch(pmaxCampaign.getId(), pmaxCampaign.getName(), 'PERFORMANCE_MAX');
      }
    } catch (err) {
      Logger.log('JunkTerms could not list Performance Max campaigns: ' + err);
    }
  }
  var keywords = fetchActiveKeywords();
  for (var k = 0; k < keywords.length; k++) {
    var keyword = keywords[k];
    var profile = touch(keyword.campaignId, keyword.campaign, '');
    rememberGroup(profile, keyword.adGroup);
    if (profile && profile.keywords.length < 40) {
      profile.keywords.push({ text: keyword.text, adGroup: keyword.adGroup, matchType: keyword.matchType });
    }
  }
  var campaigns = [];
  for (var name in byName) {
    if (byName.hasOwnProperty(name)) campaigns.push(byName[name]);
  }
  return { keywords: keywords, campaigns: campaigns };
}

function applyNegatives(negatives, customerId) {
  var sharedKeywords = [];
  var accountItems = [];
  var applied = [];
  var manual = [];
  var pmaxItems = [];
  var plan = buildPmaxPlan([], customerId, []);
  for (var i = 0; i < negatives.length; i++) {
    var item = negatives[i];
    var keyword = formatNegative(item.text, item.matchType);
    if (!keyword) continue;
    if (!item.scope || item.scope === 'account') {
      sharedKeywords.push(keyword);
      accountItems.push(item);
    } else if (pmaxTargetFor(plan, item) || String(item.channel || '') === 'PERFORMANCE_MAX' && !plan.ok) {
      pmaxItems.push(item);
    } else {
      var result = applyCampaignNegative(item, keyword);
      if (result.manual) manual.push({ suggestionId: item.suggestionId, reason: result.reason });
      else if (result.applied) applied.push({ suggestionId: item.suggestionId });
    }
  }
  var campaignsAttached = 0;
  var listKeywords = [];
  if (sharedKeywords.length) {
    var list = getOrCreateSharedList();
    addKeywordsSafely(list, missingFromList(list, sharedKeywords));
    campaignsAttached = attachSharedList(list);
    listKeywords = readSharedListKeywords(list);
  } else {
    listKeywords = null;
  }

  plan = buildPmaxPlan(pmaxItems.concat(accountItems), customerId, listKeywords);
  var pmax = runPmaxNegatives(plan);
  for (var a = 0; a < accountItems.length; a++) {
    var note = pmaxAccountNote(plan, accountItems[a].suggestionId);
    applied.push(note ? { suggestionId: accountItems[a].suggestionId, note: note } : { suggestionId: accountItems[a].suggestionId });
  }
  for (var p = 0; p < pmaxItems.length; p++) {
    var outcome = pmaxCampaignOutcome(plan, pmaxItems[p]);
    if (outcome.applied) applied.push({ suggestionId: pmaxItems[p].suggestionId, note: outcome.note });
    else manual.push({ suggestionId: pmaxItems[p].suggestionId, reason: outcome.note });
  }

  apiPost('https://junkterms.com/api/script/ack', {
    customerId: customerId,
    applied: applied,
    manual: manual,
    campaignsAttached: campaignsAttached,
    pmaxCampaigns: pmax.campaigns,
    pmaxAdded: pmax.added
  });
  Logger.log('JunkTerms applied ' + applied.length + ' negatives. Manual: ' + manual.length + '. Campaigns linked: ' + campaignsAttached + '. Performance Max: ' + pmax.added + ' added on ' + pmax.campaigns + ' campaigns.');
}

// ---- Performance Max negatives -------------------------------------------
// Scripts have no negative-keyword methods on PerformanceMaxCampaign, so these
// go through AdsApp.mutateAll as campaign_criterion resources (negative: true).
// Account-wide approvals go on every enabled PMax campaign, the way the shared
// list is linked to every enabled Search and Shopping campaign. Campaign-only
// approvals go on their own PMax campaign. Exact duplicates are skipped and a
// campaign stops at PMAX_NEGATIVE_LIMIT.
// https://developers.google.com/google-ads/api/performance-max/getting-started
// https://developers.google.com/google-ads/scripts/docs/features/mutate
var PMAX_NEGATIVE_LIMIT = 10000;
var PMAX_MUTATE_BATCH = 1000;
var PMAX_SYNCED_PROPERTY = 'JUNKTERMS_PMAX_SYNCED';

function previewPmaxNegatives(negatives, customerId) {
  var pmaxItems = [];
  var accountItems = [];
  var probe = buildPmaxPlan([], customerId, []);
  for (var i = 0; i < negatives.length; i++) {
    var item = negatives[i];
    if (!formatNegative(item.text, item.matchType)) continue;
    if (!item.scope || item.scope === 'account') accountItems.push(item);
    else if (pmaxTargetFor(probe, item)) pmaxItems.push(item);
  }
  var plan = buildPmaxPlan(pmaxItems.concat(accountItems), customerId, null);
  logPmaxPlan(plan, true);
}

function buildPmaxPlan(items, customerId, listKeywords) {
  var plan = { ok: true, error: '', customerId: String(customerId || '').split('-').join(''), campaigns: {}, order: [], byName: {}, synced: readPmaxSynced(), backfill: {} };
  try {
    var rows = AdsApp.search([
      'SELECT campaign.id, campaign.name, campaign.status',
      'FROM campaign',
      "WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'",
      "AND campaign.status != 'REMOVED'"
    ].join(' '));
    while (rows.hasNext()) {
      var row = rows.next();
      var id = String(readField(row, ['campaign', 'id'], 'campaign.id') || '');
      if (!id) continue;
      var name = String(readField(row, ['campaign', 'name'], 'campaign.name') || '');
      plan.campaigns[id] = {
        id: id,
        name: name,
        enabled: String(readField(row, ['campaign', 'status'], 'campaign.status') || '') === 'ENABLED',
        resourceName: 'customers/' + plan.customerId + '/campaigns/' + id,
        have: {},
        count: 0,
        entries: [],
        queued: {}
      };
      plan.order.push(id);
      if (name) plan.byName[name] = id;
    }
  } catch (err) {
    plan.ok = false;
    plan.error = 'Could not read Performance Max campaigns: ' + err;
    Logger.log('JunkTerms ' + plan.error);
    return plan;
  }
  if (!plan.order.length || !items.length && !hasUnsynced(plan)) return plan;

  try {
    var existing = AdsApp.search([
      'SELECT campaign.id, campaign_criterion.keyword.text, campaign_criterion.keyword.match_type',
      'FROM campaign_criterion',
      "WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'",
      "AND campaign.status != 'REMOVED'",
      'AND campaign_criterion.negative = TRUE',
      "AND campaign_criterion.type = 'KEYWORD'"
    ].join(' '));
    while (existing.hasNext()) {
      var neg = existing.next();
      var owner = plan.campaigns[String(readField(neg, ['campaign', 'id'], 'campaign.id') || '')];
      if (!owner) continue;
      owner.count++;
      owner.have[negativeKey(
        readField(neg, ['campaignCriterion', 'keyword', 'text'], 'campaign_criterion.keyword.text'),
        readField(neg, ['campaignCriterion', 'keyword', 'matchType'], 'campaign_criterion.keyword.match_type')
      )] = true;
    }
  } catch (err) {
    // Without the current negatives the duplicate check and the limit cannot be
    // trusted, so nothing is written to Performance Max this run.
    plan.ok = false;
    plan.error = 'Could not read the current Performance Max negatives: ' + err;
    Logger.log('JunkTerms ' + plan.error);
    return plan;
  }

  for (var i = 0; i < items.length; i++) {
    var item = items[i];
    if (!item.scope || item.scope === 'account') {
      for (var c = 0; c < plan.order.length; c++) {
        if (plan.campaigns[plan.order[c]].enabled) queuePmax(plan, plan.campaigns[plan.order[c]], item.text, item.matchType, item.suggestionId);
      }
    } else {
      var target = pmaxTargetFor(plan, item);
      if (target) queuePmax(plan, target, item.text, item.matchType, item.suggestionId);
    }
  }
  // A PMax campaign this script has not synced yet also gets the account
  // negatives already on the JunkTerms list, once.
  for (var b = 0; b < plan.order.length; b++) {
    var campaign = plan.campaigns[plan.order[b]];
    if (!campaign.enabled || plan.synced[syncKey(plan, campaign)]) continue;
    plan.backfill[campaign.id] = true;
    if (listKeywords === null) listKeywords = readSharedListKeywords();
    for (var k = 0; k < listKeywords.length; k++) {
      queuePmax(plan, campaign, listKeywords[k].text, listKeywords[k].matchType, '');
    }
  }
  return plan;
}

function hasUnsynced(plan) {
  for (var i = 0; i < plan.order.length; i++) {
    var campaign = plan.campaigns[plan.order[i]];
    if (campaign.enabled && !plan.synced[syncKey(plan, campaign)]) return true;
  }
  return false;
}

function pmaxTargetFor(plan, item) {
  if (!plan.ok) return null;
  var id = String(item.campaignId || '');
  if (id && plan.campaigns[id]) return plan.campaigns[id];
  var name = String(item.campaign || '');
  if (!id && name && plan.byName[name]) return plan.campaigns[plan.byName[name]];
  return null;
}

function queuePmax(plan, campaign, text, matchType, suggestionId) {
  var clean = cleanNegativeText(text);
  if (!clean) return;
  var type = pmaxMatchType(matchType);
  var key = negativeKey(clean, type);
  var entry = campaign.queued[key];
  if (!entry) {
    var status = campaign.have[key] ? 'already' : 'add';
    if (status === 'add') {
      if (campaign.count >= PMAX_NEGATIVE_LIMIT) status = 'full';
      else campaign.count++;
    }
    entry = { text: clean, matchType: type, key: key, status: status, error: '', ids: [] };
    campaign.queued[key] = entry;
    campaign.entries.push(entry);
  }
  if (suggestionId) entry.ids.push(String(suggestionId));
}

function runPmaxNegatives(plan) {
  var totals = { added: 0, campaigns: 0 };
  if (!plan.ok || !plan.order.length) return totals;
  var operations = [];
  var refs = [];
  for (var i = 0; i < plan.order.length; i++) {
    var campaign = plan.campaigns[plan.order[i]];
    for (var e = 0; e < campaign.entries.length; e++) {
      var entry = campaign.entries[e];
      if (entry.status !== 'add') continue;
      operations.push({
        campaignCriterionOperation: {
          create: {
            campaign: campaign.resourceName,
            negative: true,
            keyword: { text: entry.text, matchType: entry.matchType }
          }
        }
      });
      refs.push(entry);
    }
  }
  var outOfTime = false;
  for (var start = 0; start < operations.length; start += PMAX_MUTATE_BATCH) {
    var batch = operations.slice(start, start + PMAX_MUTATE_BATCH);
    if (remainingSeconds() < 120) {
      outOfTime = true;
      for (var t = start; t < operations.length; t++) {
        refs[t].status = 'failed';
        refs[t].error = 'The script ran out of time. It retries on the next run.';
      }
      break;
    }
    var results = null;
    try {
      results = AdsApp.mutateAll(batch, { partialFailure: true });
    } catch (err) {
      for (var f = 0; f < batch.length; f++) {
        refs[start + f].status = 'failed';
        refs[start + f].error = String(err);
      }
      continue;
    }
    for (var r = 0; r < batch.length; r++) {
      var ref = refs[start + r];
      var result = results && results[r];
      if (result && result.isSuccessful && result.isSuccessful()) {
        ref.status = 'added';
      } else {
        ref.status = 'failed';
        var messages = result && result.getErrorMessages ? result.getErrorMessages() : [];
        ref.error = messages && messages.length ? messages.join('; ') : 'Google Ads did not confirm the negative.';
      }
    }
  }
  logPmaxPlan(plan, false);
  var synced = plan.synced;
  for (var c = 0; c < plan.order.length; c++) {
    var item = plan.campaigns[plan.order[c]];
    var added = 0;
    for (var n = 0; n < item.entries.length; n++) if (item.entries[n].status === 'added') added++;
    totals.added += added;
    if (added) totals.campaigns++;
    if (plan.backfill[item.id] && !outOfTime) synced[syncKey(plan, item)] = true;
  }
  if (!outOfTime) writePmaxSynced(synced);
  return totals;
}

function logPmaxPlan(plan, preview) {
  if (!plan.ok) {
    Logger.log('JunkTerms Performance Max: nothing ' + (preview ? 'would be' : 'was') + ' written. ' + plan.error);
    return;
  }
  for (var i = 0; i < plan.order.length; i++) {
    var campaign = plan.campaigns[plan.order[i]];
    if (!campaign.entries.length) continue;
    var counts = { add: [], added: [], already: 0, full: [], failed: [] };
    for (var e = 0; e < campaign.entries.length; e++) {
      var entry = campaign.entries[e];
      var label = formatNegative(entry.text, entry.matchType === 'EXACT' ? 'exact' : 'phrase');
      if (entry.matchType === 'BROAD') label = entry.text;
      if (entry.status === 'already') counts.already++;
      else if (entry.status === 'full') counts.full.push(label);
      else if (entry.status === 'failed') counts.failed.push(label + ' (' + entry.error + ')');
      else if (entry.status === 'added') counts.added.push(label);
      else counts.add.push(label);
    }
    var head = 'JunkTerms Performance Max "' + campaign.name + '" (' + campaign.id + ')' + (plan.backfill[campaign.id] ? ', first sync of the JunkTerms list' : '') + ': ';
    if (preview) {
      Logger.log(head + 'PREVIEW would add ' + counts.add.length + ', already there ' + counts.already + ', over the ' + PMAX_NEGATIVE_LIMIT + ' limit ' + counts.full.length + '.');
      logChunks('JunkTerms   would add: ', counts.add);
    } else {
      Logger.log(head + 'added ' + counts.added.length + ', already there ' + counts.already + ', failed ' + counts.failed.length + ', over the ' + PMAX_NEGATIVE_LIMIT + ' limit ' + counts.full.length + '.');
      logChunks('JunkTerms   added: ', counts.added);
      logChunks('JunkTerms   failed: ', counts.failed);
    }
    logChunks('JunkTerms   skipped, campaign full: ', counts.full);
  }
}

function logChunks(prefix, items) {
  for (var i = 0; i < items.length; i += 50) {
    Logger.log(prefix + items.slice(i, i + 50).join(', '));
  }
}

function pmaxCampaignOutcome(plan, item) {
  if (!plan.ok) return { applied: false, note: 'Performance Max: not added. ' + plan.error + ' Add it in Google Ads or wait for the next run.' };
  var campaign = pmaxTargetFor(plan, item);
  if (!campaign) return { applied: false, note: 'Performance Max campaign not found: ' + String(item.campaign || item.campaignId || '') };
  var entry = campaign.queued[negativeKey(cleanNegativeText(item.text), pmaxMatchType(item.matchType))];
  var where = 'Performance Max campaign ' + campaign.name;
  if (!entry) return { applied: false, note: where + ': this negative could not be read.' };
  if (entry.status === 'added') return { applied: true, note: 'Added as a negative on ' + where + '.' };
  if (entry.status === 'already') return { applied: true, note: 'Already a negative on ' + where + '.' };
  if (entry.status === 'full') return { applied: false, note: where + ' already has ' + PMAX_NEGATIVE_LIMIT + ' negative keywords, the Google Ads limit. Remove some there, then add this one by hand.' };
  return { applied: false, note: 'Google Ads rejected this negative on ' + where + ': ' + entry.error };
}

function pmaxAccountNote(plan, suggestionId) {
  if (!plan.ok) return 'Not added to Performance Max. ' + plan.error;
  var done = 0;
  var total = 0;
  var problems = [];
  for (var i = 0; i < plan.order.length; i++) {
    var campaign = plan.campaigns[plan.order[i]];
    for (var e = 0; e < campaign.entries.length; e++) {
      var entry = campaign.entries[e];
      if (entry.ids.indexOf(String(suggestionId)) < 0) continue;
      total++;
      if (entry.status === 'added' || entry.status === 'already') done++;
      else if (entry.status === 'full') problems.push(campaign.name + ' is at the ' + PMAX_NEGATIVE_LIMIT + ' limit');
      else problems.push(campaign.name + ': ' + entry.error);
    }
  }
  if (!total) return '';
  var note = done === total
    ? 'Also on ' + total + ' Performance Max ' + (total === 1 ? 'campaign' : 'campaigns') + '.'
    : 'On ' + done + ' of ' + total + ' Performance Max campaigns. Not added: ' + problems.join('; ');
  return note.substring(0, 480);
}

function readSharedListKeywords(list) {
  var out = [];
  try {
    if (!list) {
      var found = AdsApp.negativeKeywordLists().withCondition('Name = "' + SHARED_LIST_NAME + '"').get();
      if (!found.hasNext()) return out;
      list = found.next();
    }
    var iter = list.negativeKeywords().get();
    while (iter.hasNext()) {
      var keyword = iter.next();
      out.push({ text: keyword.getText(), matchType: keyword.getMatchType() });
    }
  } catch (err) {
    Logger.log('JunkTerms could not read the shared list for Performance Max: ' + err);
  }
  return out;
}

function cleanNegativeText(text) {
  var clean = String(text || '').split('[').join('').split(']').join('').split('"').join('');
  return clean.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
}

function pmaxMatchType(matchType) {
  var value = String(matchType || '').toUpperCase();
  if (value.indexOf('EXACT') >= 0) return 'EXACT';
  if (value.indexOf('BROAD') >= 0) return 'BROAD';
  return 'PHRASE';
}

function negativeKey(text, matchType) {
  return pmaxMatchType(matchType) + '|' + cleanNegativeText(text).toLowerCase();
}

function syncKey(plan, campaign) {
  return plan.customerId + ':' + campaign.id;
}

function readPmaxSynced() {
  var out = {};
  try {
    var raw = PropertiesService.getScriptProperties().getProperty(PMAX_SYNCED_PROPERTY) || '';
    var parts = raw.split(',');
    for (var i = 0; i < parts.length; i++) if (parts[i]) out[parts[i]] = true;
  } catch (err) {
    Logger.log('JunkTerms could not read the Performance Max sync list: ' + err);
  }
  return out;
}

function writePmaxSynced(synced) {
  var keys = [];
  for (var key in synced) if (synced.hasOwnProperty(key)) keys.push(key);
  try {
    PropertiesService.getScriptProperties().setProperty(PMAX_SYNCED_PROPERTY, keys.join(','));
  } catch (err) {
    Logger.log('JunkTerms could not store the Performance Max sync list: ' + err);
  }
}

function remainingSeconds() {
  try {
    return Number(AdsApp.getExecutionInfo().getRemainingTime());
  } catch (err) {
    return 1800;
  }
}

function applyCampaignNegative(item, keyword) {
  var channel = String(item.channel || '');
  var campaign = findCampaign(item);
  if (!campaign) {
    return { manual: true, reason: 'Campaign not found: ' + String(item.campaign || item.campaignId || '') };
  }
  try {
    if (campaign.getAdvertisingChannelType) channel = String(campaign.getAdvertisingChannelType()) || channel;
  } catch (err) {
    channel = channel;
  }
  var pmax = channel === 'PERFORMANCE_MAX';
  if (typeof campaign.createNegativeKeyword !== 'function') {
    if (pmax) {
      return { manual: true, reason: 'Performance Max: the script could not match this campaign for an automatic negative. Add it in Google Ads.' };
    }
    return { manual: true, reason: 'This campaign type does not support campaign-level negatives from the script.' };
  }
  if (campaignHasNegative(campaign, item)) return { applied: true };
  try {
    campaign.createNegativeKeyword(keyword);
    return { applied: true };
  } catch (err) {
    Logger.log('JunkTerms could not add a campaign negative: ' + err);
    if (pmax) {
      return { manual: true, reason: 'Performance Max rejected the negative. Add it in Google Ads: ' + err };
    }
    return { manual: true, reason: String(err) };
  }
}

function findCampaign(item) {
  var id = String(item.campaignId || '');
  var numeric = /^[0-9]+$/.test(id) ? Number(id) : null;
  if (numeric != null) {
    var byId = AdsApp.campaigns().withIds([numeric]).get();
    if (byId.hasNext()) return byId.next();
  }
  var name = String(item.campaign || '').split('"').join('');
  if (name) {
    var byName = AdsApp.campaigns().withCondition('Name = "' + name + '"').get();
    if (byName.hasNext()) return byName.next();
  }
  if (typeof AdsApp.performanceMaxCampaigns === 'function') {
    try {
      if (numeric != null) {
        var pmaxId = AdsApp.performanceMaxCampaigns().withIds([numeric]).get();
        if (pmaxId.hasNext()) return pmaxId.next();
      }
      if (name) {
        var pmaxName = AdsApp.performanceMaxCampaigns().withCondition('Name = "' + name + '"').get();
        if (pmaxName.hasNext()) return pmaxName.next();
      }
    } catch (err) {
      Logger.log('JunkTerms could not look up a Performance Max campaign: ' + err);
    }
  }
  return null;
}

function campaignHasNegative(campaign, item) {
  try {
    var clean = String(item.text || '').split('[').join('').split(']').join('').split('"').join('');
    clean = clean.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
    var iter = campaign.negativeKeywords().withCondition('KeywordText = "' + clean.split('"').join('') + '"').get();
    var wantExact = String(item.matchType).toLowerCase() === 'exact';
    while (iter.hasNext()) {
      var existing = iter.next();
      var existingExact = String(existing.getMatchType()).toUpperCase().indexOf('EXACT') >= 0;
      if (existingExact === wantExact) return true;
    }
  } catch (err) {
    Logger.log('JunkTerms could not read existing campaign negatives: ' + err);
  }
  return false;
}

function missingFromList(list, keywords) {
  var have = {};
  try {
    var iter = list.negativeKeywords().get();
    while (iter.hasNext()) {
      var existing = iter.next();
      have[formatNegative(existing.getText(), existing.getMatchType())] = true;
    }
  } catch (err) {
    Logger.log('JunkTerms could not read the shared list: ' + err);
    return keywords;
  }
  var missing = [];
  for (var i = 0; i < keywords.length; i++) {
    if (!have[keywords[i]]) missing.push(keywords[i]);
  }
  return missing;
}

function formatNegative(text, matchType) {
  var clean = String(text || '').split('[').join('').split(']').join('').split('"').join('');
  clean = clean.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
  if (!clean) return '';
  if (String(matchType).toLowerCase() === 'exact') return '[' + clean + ']';
  return '"' + clean + '"';
}

function addKeywordsSafely(list, keywords) {
  if (!keywords.length) return;
  try {
    list.addNegativeKeywords(keywords);
  } catch (err) {
    Logger.log('JunkTerms bulk add failed, trying one by one: ' + err);
    for (var i = 0; i < keywords.length; i++) {
      try {
        list.addNegativeKeywords([keywords[i]]);
      } catch (one) {
        Logger.log('JunkTerms skipped ' + keywords[i] + ': ' + one);
      }
    }
  }
}

function getOrCreateSharedList() {
  var existing = AdsApp.negativeKeywordLists()
    .withCondition('Name = "' + SHARED_LIST_NAME + '"')
    .get();
  if (existing.hasNext()) return existing.next();
  var operation = AdsApp.newNegativeKeywordListBuilder()
    .withName(SHARED_LIST_NAME)
    .build();
  return operation.getResult();
}

function attachSharedList(list) {
  var attached = 0;
  attached += attachFromSelector(list, AdsApp.campaigns()
    .withCondition('Status = ENABLED')
    .withCondition('AdvertisingChannelType = SEARCH'));
  if (typeof AdsApp.shoppingCampaigns === 'function') {
    attached += attachFromSelector(list, AdsApp.shoppingCampaigns().withCondition('Status = ENABLED'));
  }
  // PerformanceMaxCampaign has no addNegativeKeywordList today, so this attaches
  // nothing. Performance Max gets the same negatives as campaign criteria
  // through runPmaxNegatives instead.
  if (typeof AdsApp.performanceMaxCampaigns === 'function') {
    try {
      attached += attachFromSelector(list, AdsApp.performanceMaxCampaigns().withCondition('Status = ENABLED'));
    } catch (err) {
      Logger.log('JunkTerms could not scan Performance Max campaigns: ' + err);
    }
  }
  return attached;
}

function attachFromSelector(list, selector) {
  var attached = 0;
  var iter = selector.get();
  while (iter.hasNext()) {
    var campaign = iter.next();
    try {
      if (typeof campaign.addNegativeKeywordList !== 'function') continue;
      var already = campaign.negativeKeywordLists()
        .withCondition('Name = "' + SHARED_LIST_NAME + '"')
        .get();
      if (already.hasNext()) continue;
      campaign.addNegativeKeywordList(list);
      attached++;
    } catch (err) {
      Logger.log('JunkTerms could not attach the list to ' + campaign.getName() + ': ' + err);
    }
  }
  return attached;
}

function apiPost(path, body) {
  return apiRequest('post', path, body);
}

function apiGet(path) {
  return apiRequest('get', path, null);
}

function apiRequest(method, path, body) {
  var options = {
    method: method,
    muteHttpExceptions: true,
    headers: { Authorization: 'Bearer ' + JUNKTERMS_TOKEN },
    contentType: 'application/json'
  };
  if (body) options.payload = JSON.stringify(body);
  var response = UrlFetchApp.fetch(path, options);
  var code = response.getResponseCode();
  var text = response.getContentText() || '';
  if (code < 200 || code >= 300) {
    throw new Error('JunkTerms API ' + code + ' on ' + path + ' ' + text.substring(0, 300));
  }
  if (!text) return {};
  return JSON.parse(text);
}