import { defineConfig } from 'vite';
import { resolve } from 'path';
import { writeFileSync } from 'fs';

/**
 * Let the measuring pages write their results back into the source tree.
 *
 * The measurements that describe the scene library — how much frame each one
 * paints, how much it changes between songs, what it looks like structurally —
 * can only be taken by rendering, and rendering needs WebGL, which means a
 * browser. So the numbers are produced in a page and have to get from there
 * into a git-tracked file. This is that hole in the wall.
 *
 * Dev only, by construction: `apply: 'serve'` means it does not exist in a
 * build, so a deployed gallery cannot write anything. The path it may write is
 * a fixed allow-list rather than a parameter — a request body decides the
 * CONTENTS of a known file and never which file.
 */
function measurementWriter() {
    const WRITABLE = {
        '/__metadata': 'src/scenes/metadata.json',
    };

    return {
        name: 'flow-state-measurement-writer',
        apply: 'serve',
        configureServer(server) {
            server.middlewares.use((req, res, next) => {
                const target = WRITABLE[req.url];
                if (!target || req.method !== 'POST') return next();

                let body = '';
                req.on('data', (chunk) => { body += chunk; });
                req.on('end', () => {
                    try {
                        writeFileSync(resolve(process.cwd(), target), body);
                        res.statusCode = 200;
                        res.end(`wrote ${target} (${body.length} bytes)`);
                    } catch (err) {
                        res.statusCode = 500;
                        res.end(String(err && err.message));
                    }
                });
            });
        },
    };
}

export default defineConfig({
    plugins: [measurementWriter()],
    server: {
        port: 5180,
        host: '127.0.0.1',
    },
    build: {
        rollupOptions: {
            input: {
                main: resolve(process.cwd(), 'index.html'),
                checks: resolve(process.cwd(), 'checks.html'),
                debug: resolve(process.cwd(), 'debug.html'),
                gallery: resolve(process.cwd(), 'gallery.html'),
                filmstrip: resolve(process.cwd(), 'filmstrip.html'),
            },
        },
    },
});
