import { MainApp } from './babylonjs/MainApp';
import { AppConfig } from './babylonjs/AppConfig';
import configurator, { ConfiguratorParams } from './components/conf';
import auth from './components/auth';
import { on, off, once, emit } from './event/bus';
import { EventBridge } from './event/bridge';
import { KernelAdapter } from './kernel/Adapter';

declare global {
    interface Window {
        faceSDK?: Record<string, unknown>;
        yiyu?: Record<string, unknown>;
    }
}

type InitParams = {
    container?: string | HTMLCanvasElement;
    modelUrlList?: string[];
    apiConfig?: ConfiguratorParams;
    env?: {
        hdrPath?: string;
        intensity?: number;
        rotationY?: number;
        background?: boolean;
    };
};

let mainApp: MainApp | null = null;
let kernelAdapter: KernelAdapter | null = null;

const kernel = {
    // 事件工具，提供给外部订阅/退订
    on,
    off,
    once,
    emit,
    /** 初始化应用 */
    init: async function (params: InitParams): Promise<void> {
        if (!params) { console.error('params is required'); return; }

        mainApp = new MainApp();
        kernelAdapter = new KernelAdapter(mainApp);

        // 展开转接器的属性和方法到kernel对象
        Object.assign(kernel, kernelAdapter);

        const container = (typeof params.container === 'string'
            ? (document.querySelector(params.container) || document.getElementById(params.container))
            : params.container || document.querySelector('#renderDom')) as HTMLCanvasElement | null;

        if (!container) { throw new Error('Render canvas not found'); }

        mainApp.loadAConfig({
            container,
            modelUrlList: params.modelUrlList || [],
            env: params.env
        });

        await mainApp.Awake();
        await mainApp.loadModel();
    }
};

if (!window.faceSDK) {
    window.faceSDK = {};
}
window.faceSDK.kernel = kernel;

export { kernel };
