import { chromium } from 'playwright-extra';
import type { Browser, BrowserContext } from 'playwright';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import fs from 'fs';

// Apply stealth plugin with all evasion techniques
chromium.use(StealthPlugin());

let browser: Browser | null = null;

interface BrowserOptions {
	userAgent?: string;
	viewport?: { width: number; height: number };
	locale?: string;
	timezone?: string;
}

export async function initializeBrowser(): Promise<Browser> {
	if (browser) {
		return browser;
	}

	console.log('Initializing Playwright browser...');

	// Use environment variable or let Playwright use its bundled browser
	const executablePath = process.env.CHROMIUM_EXECUTABLE_PATH || '/usr/bin/google-chrome';

	const launchOptions: Parameters<typeof chromium.launch>[0] = {
		headless: true,
		args: [
			'--disable-blink-features=AutomationControlled',
			'--disable-dev-shm-usage',
			'--no-sandbox',
			'--disable-setuid-sandbox',
			'--disable-gpu'
		]
	};

	// In test environment, let Playwright use bundled browser
	if (process.env.NODE_ENV !== 'test' && process.env.VITEST !== 'true') {
		launchOptions.executablePath = executablePath;
	}

	browser = await chromium.launch(launchOptions);

	console.log('Browser initialized successfully');
	return browser;
}

export async function getBrowser(): Promise<Browser> {
	if (!browser || !browser.isConnected()) {
		if (browser) {
			console.warn('Browser is disconnected. Re-initializing...');
			try {
				await browser.close();
			} catch (e) {
				/* ignore */
			}
			browser = null;
		}
		return initializeBrowser();
	}
	return browser;
}

export async function createBrowserContext(
	authStoragePath?: string,
	options?: BrowserOptions
): Promise<BrowserContext> {
	const browserInstance = await getBrowser();

	// Default stealth options
	const defaultOptions: BrowserOptions = {
		userAgent:
			'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
		viewport: { width: 1080, height: 1920 },
		locale: 'en-US',
		timezone: 'America/New_York'
	};

	const finalOptions = { ...defaultOptions, ...options };

	// Load auth if available
	let context: BrowserContext;
	const contextOptions = {
		storageState: authStoragePath && fs.existsSync(authStoragePath) ? authStoragePath : undefined,
		userAgent: finalOptions.userAgent,
		viewport: finalOptions.viewport,
		locale: finalOptions.locale,
		timezoneId: finalOptions.timezone,
		permissions: [],
		colorScheme: 'light' as const
	};

	if (authStoragePath && fs.existsSync(authStoragePath)) {
		console.log('Loading authentication from:', authStoragePath);
	} else {
		console.warn('No auth storage found. Running as guest.');
	}

	context = await browserInstance.newContext(contextOptions);

	// Note: Anti-detection scripts are now handled automatically by the stealth plugin
	// The plugin applies 15+ evasion techniques including:
	// - navigator.webdriver masking
	// - chrome.runtime mocking
	// - User-Agent override
	// - WebGL fingerprinting evasion
	// - And many more...

	return context;
}

export async function closeBrowser(): Promise<void> {
	if (browser) {
		console.log('Closing Playwright browser...');
		await browser.close();
		browser = null;
	}
}
