#!/usr/bin/env bun
import { mkdirSync, writeFileSync } from 'fs'
import { dirname, join } from 'path'

const root = process.cwd()
const rawRoot = join(root, 'data', 'sources', 'apify', 'raw')
const token = Bun.env.APIFY_TOKEN || Bun.env.APIFY_API_TOKEN
const generatedAt = new Date().toISOString()
if (!token) throw new Error('Missing APIFY_TOKEN or APIFY_API_TOKEN')

const maxTotalChargeUsd = Number(Bun.env.APIFY_HEALTHSPAN_SERP_MAX_USD || 0.05)

function writeJson(path: string, data: any) {
  mkdirSync(dirname(path), { recursive: true })
  writeFileSync(path, JSON.stringify(data, null, 2) + '\n', 'utf8')
}

async function apify(path: string, options: RequestInit = {}) {
  const sep = path.includes('?') ? '&' : '?'
  const res = await fetch(`https://api.apify.com${path}${sep}token=${encodeURIComponent(token!)}`, {
    ...options,
    headers: { 'Content-Type': 'application/json', ...(options.headers || {}) }
  })
  const text = await res.text()
  let data: any
  try { data = text ? JSON.parse(text) : null } catch { data = text }
  if (!res.ok) throw new Error(`Apify ${res.status} ${res.statusText}: ${typeof data === 'string' ? data : JSON.stringify(data)}`)
  return data
}

async function waitForRun(runId: string, timeoutMs = 1000 * 60 * 6) {
  const started = Date.now()
  let run = (await apify(`/v2/actor-runs/${runId}`)).data
  while (!['SUCCEEDED', 'FAILED', 'ABORTED', 'TIMED-OUT'].includes(run.status)) {
    if (Date.now() - started > timeoutMs) throw new Error(`Timed out waiting for ${runId}`)
    await new Promise(resolve => setTimeout(resolve, 5000))
    run = (await apify(`/v2/actor-runs/${runId}`)).data
    console.log(`${runId}: ${run.status} usd=${run.usageTotalUsd || 0}`)
  }
  return run
}

const input = {
  queries: [
    'site:healthspan.co.uk/optivision Healthspan OptiVision lutein zeaxanthin omega 3',
    'site:healthspan.co.uk OptiVision eye health supplement Healthspan'
  ].join('\n'),
  resultsPerPage: 10,
  maxPagesPerQuery: 1,
  countryCode: 'gb',
  searchLanguage: 'en',
  languageCode: 'en',
  mobileResults: false,
  includeUnfilteredResults: false,
  saveHtml: false,
  saveHtmlToKeyValueStore: false,
  includeIcons: false,
  aiMode: 'aiModeOff',
  perplexitySearch: { enablePerplexity: false, returnImages: false, returnRelatedQuestions: false },
  chatGptSearch: { enableChatGpt: false },
  proxyConfiguration: { useApifyProxy: true, apifyProxyGroups: ['GOOGLE_SERP'] }
}

console.log(`Starting apify/google-search-scraper for Healthspan OptiVision SERP fallback, maxPagesPerQuery=1, cap=$${maxTotalChargeUsd}`)
const start = await apify(`/v2/acts/apify~google-search-scraper/runs?maxTotalChargeUsd=${maxTotalChargeUsd}`, {
  method: 'POST',
  body: JSON.stringify(input)
})
const run = await waitForRun(start.data.id)
const rawItems = run.defaultDatasetId ? await apify(`/v2/datasets/${run.defaultDatasetId}/items?clean=true`) : []
const items = Array.isArray(rawItems) ? rawItems.map((item: any) => ({
  ...item,
  sku: 'JV-VISISOFT',
  sourceType: 'competitor_serp_fallback',
  label: 'Healthspan OptiVision Google SERP fallback',
  competitor: 'Healthspan',
  matchContext: 'competitor_serp_fallback',
  note: 'Fallback raw source because direct Healthspan PDP browser/content crawls returned 0 items.'
})) : rawItems

const result = {
  capturedAt: generatedAt,
  job: 'healthspan-serp',
  actor: 'apify/google-search-scraper',
  maxTotalChargeUsd,
  input,
  run: {
    id: run.id,
    status: run.status,
    statusMessage: run.statusMessage,
    defaultDatasetId: run.defaultDatasetId,
    startedAt: run.startedAt,
    finishedAt: run.finishedAt,
    usageTotalUsd: run.usageTotalUsd,
    usage: run.usage,
    stats: run.stats
  },
  itemCount: Array.isArray(items) ? items.length : 0,
  items
}

const stamp = generatedAt.replace(/[:.]/g, '-')
writeJson(join(rawRoot, `top3-specialist-healthspan-serp-${stamp}.json`), result)
writeJson(join(rawRoot, 'top3-specialist-healthspan-serp-latest.json'), result)
console.log(`Healthspan SERP fallback ${run.status}: ${result.itemCount} items, usd=${run.usageTotalUsd || 0}`)
