import { chromium } from 'playwright'

const baseUrl = (process.env.BASE_URL || 'https://explorer.d-bis.org').replace(/\/$/, '')
const viewportHeight = Number(process.env.SMOKE_VIEWPORT_HEIGHT || 720)
const maxViewportHeights = Number(process.env.SMOKE_MAX_VIEWPORT_HEIGHTS || 2.5)

const routeLimits = new Map(
  (process.env.SMOKE_SCROLL_ROUTE_LIMITS || ' /=4,/operator=4,/transactions=3')
    .split(',')
    .map((entry) => entry.trim())
    .filter(Boolean)
    .map((entry) => {
      const [path, limit] = entry.split('=')
      return [path, Number(limit)]
    }),
)

function limitForRoute(path) {
  return routeLimits.get(path) ?? maxViewportHeights
}

const routes = [
  '/',
  '/bridge',
  '/routes',
  '/operations',
  '/system',
  '/operator',
  '/analytics',
  '/liquidity',
  '/blocks',
  '/transactions',
  '/addresses',
  '/wallet',
  '/access',
]

async function main() {
  const browser = await chromium.launch({ headless: true })
  const page = await browser.newPage({
    viewport: { width: 1280, height: viewportHeight },
  })
  let failures = 0

  for (const path of routes) {
    const url = `${baseUrl}${path}`

    try {
      const response = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 20000 })
      await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})

      if (!response || !response.ok()) {
        console.error(`FAIL ${path}: HTTP ${response ? response.status() : 'no-response'}`)
        failures += 1
        continue
      }

      const scrollHeight = await page.evaluate(() => document.documentElement.scrollHeight)
      const routeLimit = limitForRoute(path)
      const limit = viewportHeight * routeLimit

      if (scrollHeight > limit) {
        console.error(
          `FAIL ${path}: scrollHeight ${scrollHeight}px exceeds ${routeLimit}× viewport (${Math.round(limit)}px)`,
        )
        failures += 1
        continue
      }

      console.log(`OK   ${path} (${scrollHeight}px)`)
    } catch (error) {
      console.error(`FAIL ${path}: ${error instanceof Error ? error.message : String(error)}`)
      failures += 1
    }
  }

  await browser.close()

  if (failures > 0) {
    process.exitCode = 1
    return
  }

  console.log(`Scroll-height smoke passed for ${routes.length} routes at ${viewportHeight}px viewport`)
}

main().catch((error) => {
  console.error(error instanceof Error ? error.stack || error.message : String(error))
  process.exitCode = 1
})
