const assproc = require('@railcomm/assproc');
const { join: pathJoin } = require('path');
const fs = require('fs');

(async () => {
    const env = {
        root: __dirname,
        source: pathJoin(__dirname, 'assets'),
        public: pathJoin(__dirname, 'public'),
        debug: !!process.env.MSZ_DEBUG,
        swc: { es: 'es2021' },
        housekeep: [ pathJoin(__dirname, 'public', 'assets') ],
    };

    const tasks = {
        js: [
            { source: 'common.js', target: '/assets', name: 'common.{hash}.js', },
            { source: 'misuzu.js', target: '/assets', name: 'misuzu.{hash}.js', },
            { source: 'oauth2.js', target: '/assets', name: 'oauth2.{hash}.js', },
            { source: 'redirects.js', target: '/assets', name: 'redirects.{hash}.js', },
        ],
        css: [
            { source: 'errors.css', target: '/', name: 'errors.css', },
            { source: 'common.css', target: '/assets', name: 'common.{hash}.css', },
            { source: 'misuzu.css', target: '/assets', name: 'misuzu.{hash}.css', },
            { source: 'oauth2.css', target: '/assets', name: 'oauth2.{hash}.css', },
            { source: 'redirects.css', target: '/assets', name: 'redirects.{hash}.css', },
        ],
        twig: [
            { source: 'errors/400', target: '/', name: 'error-400.html', },
            { source: 'errors/401', target: '/', name: 'error-401.html', },
            { source: 'errors/402', target: '/', name: 'error-402.html', },
            { source: 'errors/403', target: '/', name: 'error-403.html', },
            { source: 'errors/404', target: '/', name: 'error-404.html', },
            { source: 'errors/405', target: '/', name: 'error-405.html', },
            { source: 'errors/410', target: '/', name: 'error-410.html', },
            { source: 'errors/451', target: '/', name: 'error-451.html', },
            { source: 'errors/500', target: '/', name: 'error-500.html', },
            { source: 'errors/502', target: '/', name: 'error-502.html', },
            { source: 'errors/503', target: '/', name: 'error-503.html', },
        ],
    };

    const infoPath = process.env.ASSET_INFO_PATH ?? pathJoin(__dirname, 'assets/current.json');
    let files = {};

    if(process.argv.length > 2) {
        files = JSON.parse(fs.readFileSync(infoPath));

        const filter = process.argv.slice(2);
        for(const name in tasks)
            if(!filter.includes(name))
                delete tasks[name];
    }

    fs.writeFileSync(infoPath, JSON.stringify({
        ...files,
        ...await assproc.process(env, tasks),
    }));
})();