const { chromium } = require('playwright')
const fs = require('fs')
const path = require('path')
const http = require('http')
const https = require('https')

async function captureScreenshot(codeOrUrl, options = {}) {
  const { maxWidth = 500, aspectRatio } = options
  const browser = await chromium.launch()
  const page = await browser.newPage()

  try {
    // Set viewport to maintain aspect ratio
    let viewportWidth = maxWidth
    let viewportHeight = Math.round(maxWidth * (aspectRatio || 16 / 9))

    await page.setViewportSize({ width: viewportWidth, height: viewportHeight })

    // Check if it's a URL or code
    if (codeOrUrl.startsWith('http://') || codeOrUrl.startsWith('https://')) {
      // It's a URL
      await page.goto(codeOrUrl, { waitUntil: 'networkidle' })
    } else if (fs.existsSync(codeOrUrl)) {
      // It's a file path
      const filePath = path.resolve(codeOrUrl)
      const fileUrl = `file://${filePath}`
      await page.goto(fileUrl, { waitUntil: 'networkidle' })
    } else {
      // Assume it's HTML code
      await page.setContent(codeOrUrl, { waitUntil: 'networkidle' })
    }

    // Wait a bit for any dynamic content
    await page.waitForTimeout(1000)

    // Take screenshot
    const screenshot = await page.screenshot({
      type: 'png',
      fullPage: false,
    })

    await browser.close()
    return screenshot
  } catch (error) {
    await browser.close()
    throw new Error(`Screenshot capture failed: ${error.message}`)
  }
}

async function captureScreenshotFromCode(htmlCode, options = {}) {
  return captureScreenshot(htmlCode, options)
}

async function captureScreenshotFromUrl(url, options = {}) {
  return captureScreenshot(url, options)
}

function screenshotToBase64(screenshotBuffer) {
  return screenshotBuffer.toString('base64')
}

function screenshotToDataUrl(screenshotBuffer) {
  return `data:image/png;base64,${screenshotToBase64(screenshotBuffer)}`
}

module.exports = {
  captureScreenshot,
  captureScreenshotFromCode,
  captureScreenshotFromUrl,
  screenshotToBase64,
  screenshotToDataUrl,
}

