const argv = (str) => {
	const idx = process.argv.findIndex((a) => a.startsWith(str))
	if (idx > -1) {
		return process.argv[idx].substring(str.length + 1)
	}
	return null
}

const isWebComponent = process.argv.includes('wc') || process.argv.includes('wc=1') || process.argv.some((arg) => arg.startsWith('wc='))

if (!process.env.GENERATE_SOURCEMAP) {
	process.env.GENERATE_SOURCEMAP = 'false'
	console.log('process.env.GENERATE_SOURCEMAP', process.env.GENERATE_SOURCEMAP)
}

if (!process.env.BUILD_PATH) {
	process.env.BUILD_PATH = isWebComponent ? './out_wc' : './out'
	console.log('process.env.BUILD_PATH', process.env.BUILD_PATH)
}

if (isWebComponent) {
	process.env.REACT_APP_WEB_COMPONENT = '1'
	process.env.REACT_APP_USTORE_REMOTE_SERVER_URL = /^https?:\/\//.test(argv('server') || '') ? argv('server') : ''
}

if (process.argv.length <= 2 || (process.argv.indexOf('wc=1') > -1 && process.argv.length === 3)) {
	console.log('Applying features config...')
	const applyFeaturesConfig = require('./src/ustore-internal/scripts/applyFeaturesConfig.js')
	applyFeaturesConfig()
}

const { spawn } = require('child_process')
const path = require('path')

const isWindows = process.platform === 'win32'

let webpackCliPath
try {
	webpackCliPath = require.resolve('webpack-cli/bin/cli.js')
} catch (e) {
	console.error('webpack-cli not found. Please run: npm install')
	process.exit(1)
}

const webpackArgs = [
	webpackCliPath,
	'--mode',
	'production',
	'--config',
	'./webpack/webpack.config.js',
]

if (isWindows) {
	const nodeCommand = process.execPath
	const escapedNodePath = `"${nodeCommand}"`
	const command = `${escapedNodePath} ${webpackArgs
		.map((arg) => `"${arg}"`)
		.join(' ')}`

	const webpackProcess = spawn(command, [], {
		stdio: 'inherit',
		cwd: __dirname,
		env: {
			...process.env,
		},
		shell: true,
	})

	webpackProcess.on('error', (err) => {
		console.error('Failed to start webpack:', err)
		process.exit(1)
	})

	webpackProcess.on('close', (code) => {
		process.exit(code)
	})
} else {
	const nodeCommand = process.execPath
	const webpackProcess = spawn(nodeCommand, webpackArgs, {
		stdio: 'inherit',
		cwd: __dirname,
		env: {
			...process.env,
		},
	})

	webpackProcess.on('error', (err) => {
		console.error('Failed to start webpack:', err)
		if (err.code === 'ENOENT') {
			console.error(`Node.js not found at: ${nodeCommand}`)
			console.error('Please ensure Node.js is installed')
		}
		process.exit(1)
	})

	webpackProcess.on('close', (code) => {
		process.exit(code)
	})
}
