import { createApp } from 'vue';
import {
	setConfig,
	jingrowRequest,
	pageMetaPlugin,
	resourcesPlugin,
} from 'jingrow-ui';
import App from './App.vue';
import router from './router';
import { initSocket } from './socket';
import { subscribeToJobUpdates } from './utils/agentJob';
import { fetchPlans } from './data/plans.js';
import * as Sentry from '@sentry/vue';
import { session } from './data/session.js';
import { unreadNotificationsCount } from './data/notifications.js';
import { initI18n } from './utils/i18n';
import './vendor/posthog.js';

const request = (options) => {
	const _options = options || {};
	_options.headers = options.headers || {};
	const currentTeam =
		localStorage.getItem('current_team') || window.default_team;
	if (currentTeam) {
		_options.headers['X-Jcloud-Team'] = currentTeam;
	}
	return jingrowRequest(_options);
};
setConfig('resourceFetcher', request);
setConfig('defaultListUrl', 'jcloud.api.client.get_list');
setConfig('defaultDocGetUrl', 'jcloud.api.client.get');
setConfig('defaultDocInsertUrl', 'jcloud.api.client.insert');
setConfig('defaultRunDocMethodUrl', 'jcloud.api.client.run_pg_method');
setConfig('defaultDocUpdateUrl', 'jcloud.api.client.set_value');
setConfig('defaultDocDeleteUrl', 'jcloud.api.client.delete');

let app;
let socket;

getInitialData().then(async () => {
	// 初始化 i18n（在创建 app 之前）
	await initI18n();
	
	app = createApp(App);
	app.use(router);
	app.use(resourcesPlugin);
	app.use(pageMetaPlugin);

	socket = initSocket();
	app.config.globalProperties.$socket = socket;
	window.$socket = socket;
	subscribeToJobUpdates(socket);
	if (session.isLoggedIn) {
		fetchPlans();
		session.roles.fetch();
		unreadNotificationsCount.fetch();
	}

	if (window.jcloud_dashboard_sentry_dsn.includes('https://')) {
		Sentry.init({
			app,
			dsn: window.jcloud_dashboard_sentry_dsn,
			integrations: [
				Sentry.browserTracingIntegration({ router }),
				Sentry.replayIntegration({
					maskAllText: false,
					blockAllMedia: false,
				}),
				Sentry.thirdPartyErrorFilterIntegration({
					// Specify the application keys that you specified in the Sentry bundler plugin
					filterKeys: ['jcloud-dashboard'],

					// Defines how to handle errors that contain third party stack frames.
					// Possible values are:
					// - 'drop-error-if-contains-third-party-frames'
					// - 'drop-error-if-exclusively-contains-third-party-frames'
					// - 'apply-tag-if-contains-third-party-frames'
					// - 'apply-tag-if-exclusively-contains-third-party-frames'
					behaviour: 'apply-tag-if-contains-third-party-frames',
				}),
			],
			replaysSessionSampleRate: 0.1,
			replaysOnErrorSampleRate: 1.0,
			beforeSend(event, hint) {
				const ignoreErrors = [
					/api\/action\/jcloud.api.client/,
					/dynamically imported module/,
					/NetworkError when attempting to fetch resource/,
					/Failed to fetch/,
					/Load failed/,
					/jingrow is not defined/,
					/Cannot read properties of undefined \(reading 'exc_type'\)/,
					/Failed to execute 'transaction' on 'IDBDatabase': The database connection is closing/,
					/Importing a module script failed./,
					/o is undefined/,
					/undefined is not an object \(evaluating 'o.exc_type'\)/,
					/e is not defined/,
					/Cannot set property ethereum of #<Window> which has only a getter/,
					/Can't find variable: ResizeObserver/,
					/Method not found/,
					/Menu caption text is required/,
					/Internal error opening backing store for indexedDB.open/,
				];
				const ignoreErrorTypes = [
					'BuildValidationError',
					'ValidationError',
					'PermissionError',
					'SecurityException',
					'AAAARecordExists',
					'AuthenticationError',
					'RateLimitExceededError',
					'InsufficientSpaceOnServer',
					'ConflictingDNSRecord',
					'MultipleARecords',
				];
				const error = hint.originalException;

				if (
					error?.name === 'DashboardError' ||
					ignoreErrorTypes.includes(error?.exc_type) ||
					(error?.message && ignoreErrors.some((re) => re.test(error.message)))
				) {
					return null;
				}

				return event;
			},
			logErrors: true,
		});

		Sentry.setTag('team', localStorage.getItem('current_team'));
	}

	if (
		window.jcloud_frontend_posthog_project_id &&
		window.jcloud_frontend_posthog_host &&
		window.posthog
	) {
		window.posthog.init(window.jcloud_frontend_posthog_project_id, {
			api_host: window.jcloud_frontend_posthog_host,
			person_profiles: 'identified_only',
			autocapture: false,
			disable_session_recording: true,
			session_recording: {
				maskAllInputs: true,
			},
		});
	} else {
		// unset posthog if not configured
		window.posthog = undefined;
	}

	importGlobals().then(() => {
		app.mount('#app');
	});
});

function getInitialData() {
	if (import.meta.env.DEV) {
		// 使用 GET 请求避免 CSRF token 问题
		return jingrowRequest({
			url: '/api/action/jcloud.www.dashboard.get_context_for_dev',
			method: 'GET'
		}).then((values) => Object.assign(window, values));
	} else {
		return Promise.resolve();
	}
}

function importGlobals() {
	return import('./globals.ts').then((globals) => {
		app.use(globals.default);
	});
}
