const fs = require("fs");
const path = require("path");
const { loadEnv } = require("../utils/env");
const logger = require("../utils/logger");

loadEnv();

function boolFromEnv(name, fallback) {
  const raw = process.env[name];
  if (raw === undefined) return fallback;
  return ["1", "true", "yes", "on"].includes(raw.toLowerCase());
}

function numberFromEnv(name, fallback) {
  const value = Number(process.env[name]);
  return Number.isFinite(value) ? value : fallback;
}

function resolveFromBackend(rawPath) {
  if (path.isAbsolute(rawPath)) return rawPath;
  return path.join(__dirname, "..", rawPath);
}

function getBrowserConfig(accountEmail = "default") {
  const sessionRoot = resolveFromBackend(process.env.PUPPETEER_SESSION_DIR || "./sessions");
  const safeAccount = accountEmail.replace(/[^a-z0-9._-]/gi, "_");
  return {
    headless: boolFromEnv("PUPPETEER_HEADLESS", false),
    slowMo: numberFromEnv("PUPPETEER_SLOW_MO_MS", 100),
    navigationTimeoutMs: numberFromEnv("PUPPETEER_NAVIGATION_TIMEOUT_MS", 45000),
    executablePath:
      process.env.PUPPETEER_EXECUTABLE_PATH ||
      "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
    userDataDir: path.join(sessionRoot, safeAccount),
    baseUrl: process.env.SMILE_BASE_URL || "https://www.smile.one/",
  };
}

async function launchBrowser(accountEmail) {
  const puppeteer = require("puppeteer-core");
  const config = getBrowserConfig(accountEmail);
  fs.mkdirSync(config.userDataDir, { recursive: true });

  const browser = await puppeteer.launch({
    headless: config.headless,
    executablePath: config.executablePath,
    slowMo: config.slowMo,
    userDataDir: config.userDataDir,
    defaultViewport: {
      width: 1366,
      height: 900,
    },
    args: [
      "--no-sandbox",
      "--disable-setuid-sandbox",
      "--disable-dev-shm-usage",
    ],
  });

  const page = await browser.newPage();
  page.setDefaultNavigationTimeout(config.navigationTimeoutMs);
  page.setDefaultTimeout(config.navigationTimeoutMs);

  logger.info("Puppeteer browser launched", {
    accountEmail,
    headless: config.headless,
    userDataDir: config.userDataDir,
  });

  return {
    browser,
    page,
    config,
  };
}

async function smokeCheck() {
  const session = await launchBrowser("smoke-check");
  try {
    await session.page.goto(session.config.baseUrl, {
      waitUntil: "domcontentloaded",
    });
    logger.info("Puppeteer smoke check loaded Smile.one", {
      url: session.page.url(),
      title: await session.page.title(),
    });
  } finally {
    await session.browser.close();
  }
}

if (require.main === module) {
  smokeCheck().catch((error) => {
    logger.error("Puppeteer smoke check failed", {
      error: error.message,
      stack: error.stack,
    });
    process.exit(1);
  });
}

module.exports = {
  getBrowserConfig,
  launchBrowser,
};
