import {defineConfig, PluginOption} from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import {viteSingleFile} from 'vite-plugin-singlefile';
import {createHtmlPlugin} from 'vite-plugin-html';
import purgeCss from 'vite-plugin-tailwind-purgecss';
import {NormalizedInputOptions, PluginContext} from 'rollup';
import * as fs from 'fs';
import * as child_process from 'child_process';

const response_replacement =
    'interface ResponseE {\n' +
    '    e: string,\n' +
    '    o: null\n' +
    '}\n' +
    'interface ResponseO<T> {\n' +
    '    e: null,\n' +
    '    o: T\n' +
    '}\n' +
    'export type Response<T> = ResponseE | ResponseO<T>;'

function checkMrpc(this: PluginContext, options: NormalizedInputOptions) {
    const src_ts = fs.statSync('../fileserver.rs').mtimeMs;
    const update = !fs.existsSync('src/api.ts') || fs.statSync('src/api.ts').mtimeMs <= src_ts;
    if (!update)
        return;
    child_process.spawnSync(
        '../mrpc',
        ['-n', 'src/api', '-c', 'ts', '../fileserver.rs'],
        { stdio: 'inherit' }
    );
    let api_content = fs.readFileSync('src/api.ts', 'utf8');
    api_content = api_content.replace(
        'interface Response<T> {\n    e: (string|null);\n    o: (T|null);\n}',
        response_replacement
    );
    fs.writeFileSync('src/api.ts', api_content, 'utf8');
}

export default defineConfig({
    plugins: [
        { name: 'mrpc', buildStart: checkMrpc },
        svelte(),
        purgeCss(),
        viteSingleFile({removeViteModuleLoader: true}),
        createHtmlPlugin({minify: true})
    ],
    build: {
        minify: false
    },
    server: {
        host: '0.0.0.0',
        proxy: {
            '/mrpc': 'http://127.0.0.1:2121',
            '/download': 'http://127.0.0.1:2121',
            '/download_multi': 'http://127.0.0.1:2121',
            '/upload': 'http://127.0.0.1:2121'
        }
    }
})
