#!/usr/bin/env node

const webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const path = require('path')

const allArgs = process.argv.slice(2)

const serverArg = allArgs.find((arg) => arg.startsWith('server='))
const themeArg = allArgs.find((arg) => arg.startsWith('theme='))
const ducbuildArg = allArgs.find((arg) => arg.startsWith('ducbuild='))
const widgetbuildArg = allArgs.find((arg) => arg.startsWith('widgetbuild='))
const wcArg =
	allArgs.includes('--wc') || allArgs.some((arg) => arg.startsWith('wc='))

if (serverArg) {
	const serverUrl = serverArg.split('=')[1]
	process.env.REACT_APP_USTORE_REMOTE_SERVER_URL = serverUrl?.startsWith('https://') ? serverUrl : ''
	console.log('Setting server URL:', serverUrl)
}

if (themeArg) {
	const themeName = themeArg.split('=')[1]
	process.env.THEME_PAGES = themeName
	console.log('Setting theme:', themeName)
}

if (wcArg) {
	process.env.REACT_APP_WEB_COMPONENT = '1'
	if (serverArg) {
		const serverUrl = serverArg.split('=')[1]
		process.env.REACT_APP_USTORE_REMOTE_SERVER_URL = /^https?:\/\//.test(serverUrl || '') ? serverUrl : ''
	}
	console.log('Web Component mode enabled')
}

if (ducbuildArg) {
	const ducbuildValue = ducbuildArg.split('=')[1]
	process.env.REACT_APP_DUC_BUILD = ducbuildValue
	console.log('DUC build mode:', ducbuildValue)
}

if (widgetbuildArg) {
	const widgetbuildValue = widgetbuildArg.split('=')[1]
	process.env.REACT_APP_WIDGET_BUILD = widgetbuildValue
	console.log('Widgets build mode:', widgetbuildValue)
}

console.log('Applying features config...')
const applyFeaturesConfig = require('./src/ustore-internal/scripts/applyFeaturesConfig.js')
applyFeaturesConfig()

const originalArgv = process.argv
process.env.ORIGINAL_ARGV = JSON.stringify(originalArgv)

const webpackConfig = require('./webpack/webpack.config.js')({}, { mode: 'development' })

const compiler = webpack(webpackConfig)

const devServerOptions = { ...webpackConfig.devServer }
const server = new WebpackDevServer(devServerOptions, compiler)

process.on('SIGINT', () => {
	const timeout = setTimeout(() => {
		process.exit(0)
	}, 3000)

	server.stop().then(() => {
		clearTimeout(timeout)
		process.exit(0)
	}).catch(() => {
		clearTimeout(timeout)
		process.exit(1)
	})
})

process.on('SIGTERM', () => {
	const timeout = setTimeout(() => {
		process.exit(0)
	}, 3000)

	server.stop().then(() => {
		clearTimeout(timeout)
		process.exit(0)
	}).catch(() => {
		clearTimeout(timeout)
		process.exit(1)
	})
})

server.start().catch((err) => {
	console.error(err)
	process.exit(1)
})
