import { chromium, type Browser, type BrowserContext } from 'playwright';
import fs from 'fs';

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...');
	browser = await chromium.launch({
		executablePath: '/usr/bin/chromium-browser',
		headless: true,
		args: [
			'--disable-blink-features=AutomationControlled',
			'--disable-dev-shm-usage',
			'--no-sandbox',
			'--disable-setuid-sandbox',
			'--disable-gpu'
		]
	});

	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);

	// Mask automation indicators
	await context.addInitScript(() => {
		// Override navigator.webdriver
		Object.defineProperty(navigator, 'webdriver', {
			get: () => false
		});

		// Mock Chrome runtime
		(window as any).chrome = {
			runtime: {}
		};

		// Mock permissions
		const originalQuery = window.navigator.permissions.query;
		window.navigator.permissions.query = (parameters: any) =>
			parameters.name === 'notifications'
				? Promise.resolve({ state: 'denied' } as PermissionStatus)
				: originalQuery(parameters);
	});

	return context;
}

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