import * as codearts from '@codearts/plugin';
import * as path from 'path';
import { nlsConfig } from '@cloudide/nls/lib/node/main';
import { Messaging } from '@cloudide/messaging';
import { Backend } from './node/backend';

const VIEW_TYPE = 'view_type_vibedev_chat';
let htmlCache = '';
let webviewRef: codearts.WebviewView | null = null;
let messagingBound = false;

function buildHtml(context: codearts.ExtensionContext): string {
    if (htmlCache) return htmlCache;

    const pug = require('pug');
    const l10n = nlsConfig.l10n || {};
    let html = pug.renderFile(
        path.join(context.extensionPath, 'resources/page/index.pug'),
        { l10n }
    );

    // Inject acquireCloudidePluginApi if not already provided by IDE
    const script = `<script>
        if (typeof acquireCloudidePluginApi === 'undefined') {
            var acquireCloudidePluginApi = (function() {
                var acquired = false;
                var i18n = ${JSON.stringify(nlsConfig)};
                var extensionPath = "${encodeURIComponent(context.extensionPath)}";
                return function() {
                    if (acquired) throw new Error('Already acquired');
                    acquired = true;
                    return Object.freeze({
                        getViewType: function() { return '${VIEW_TYPE}'; },
                        getExtData: function() { return undefined; },
                        getI18n: function() { return i18n; },
                        getExtensionPath: function() { return decodeURIComponent(extensionPath); }
                    });
                };
            })();
        }
    </script>`;
    html = html.replace('<head>', '<head>' + script);

    // Fix resource paths
    const pageUri = codearts.Uri.file(
        path.join(context.extensionPath, 'resources/page')
    ).with({ scheme: 'theia-resource' }).toString() + '/';
    html = html.replace(/href="css\//g, 'href="' + pageUri + 'css/');
    html = html.replace(/src="dist\//g, 'src="' + pageUri + 'dist/');

    htmlCache = html;
    return htmlCache;
}

export function start(context: codearts.ExtensionContext) {
    Messaging.init('backend');
    const pluginLike = {
        call: async (identifier: string, ...args: any[]) => {
            const msg = Messaging.getInstance();
            return msg ? msg.call(identifier, ...args) : Promise.resolve();
        },
        log: (_level: string, message: string) => {
            console.log(`[VibeDev] ${message}`);
        }
    };
    const backend = new Backend(pluginLike as any, context);
    backend.init().then(() => backend.run());

    const provider: codearts.WebviewViewProvider = {
        resolveWebviewView(webviewView) {
            webviewRef = webviewView;
            webviewView.webview.options = {
                enableScripts: true,
                localResourceRoots: [
                    codearts.Uri.file(path.join(context.extensionPath, 'resources'))
                ]
            };
            webviewView.webview.html = buildHtml(context);

            // Bridge webview <-> backend messaging (only once)
            if (!messagingBound) {
                messagingBound = true;
                const adapter = {
                    registerMessageHandler: (handler: (msg: any) => void) => {
                        webviewView.webview.onDidReceiveMessage(handler);
                    },
                    postMessage: (msg: any) => {
                        webviewView.webview.postMessage(msg);
                    },
                    onDispose: (handler: () => void) => {
                        webviewView.onDidDispose(handler);
                    },
                    disposed: false
                };
                Messaging.bind(adapter as any, 'backend');
            }
        }
    };

    context.subscriptions.push(
        codearts.window.registerWebviewViewProvider(VIEW_TYPE, provider)
    );

    // Register settings command for title bar
    context.subscriptions.push(
        codearts.commands.registerCommand('vibedev.openSettings', () => {
            if (webviewRef) {
                webviewRef.webview.postMessage({ type: 'openSettings' });
            }
        })
    );
}

export function stop(_context: codearts.ExtensionContext) { }