/**
 * Copyright (c) 2026 The OpenDesk Team
 * OpenDesk is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import { createHash } from 'node:crypto';
import { cp, mkdtemp, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { basename, dirname, join, resolve } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { fileURLToPath } from 'node:url';

const root = fileURLToPath(new URL('../', import.meta.url));
const patches = join(root, 'patches');
const hash = (value) => createHash('sha256').update(value).digest('hex');
const fail = () => {
    throw new Error('webrtc preparation: fixed input mismatch; reinstall the fixed package');
};
const stripMap = (value) => value.replace(/^\/\/# sourceMappingURL=.*\r?\n?/gm, '');

// Apply only exact unified hunks. A mismatch is never repaired with fuzzy context.
function applyPatch(patch, sources) {
    const lines = patch.split('\n');
    let file;
    let cursor = 0;
    let output = [];
    let source;
    const finish = () => {
        if (file) sources.set(file, [...output, ...source.slice(cursor)].join('\n'));
    };
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        if (line.startsWith('--- a/lib/')) {
            finish();
            file = line.slice('--- a/lib/'.length);
            if (!sources.has(file)) fail();
            source = sources.get(file).split('\n');
            output = [];
            cursor = 0;
            if (lines[++i] !== `+++ b/lib/${file}`) fail();
        } else if (line.startsWith('@@ ')) {
            const match = /^@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@/.exec(line);
            if (!file || !match) fail();
            const start = Number(match[1]) - 1;
            if (start < cursor) fail();
            output.push(...source.slice(cursor, start));
            cursor = start;
            while (i + 1 < lines.length && /^[ +-]/.test(lines[i + 1]) && !lines[i + 1].startsWith('--- a/')) {
                const entry = lines[++i];
                if (entry[0] !== '+') {
                    if (source[cursor++] !== entry.slice(1)) fail();
                }
                if (entry[0] !== '-') output.push(entry.slice(1));
            }
        } else if (line !== '') fail();
    }
    finish();
}

// Serialise only the directory swap. Independent builds may prepare their own staging trees.
async function replaceBuild(stagedLib, output, previous) {
    const lock = join(dirname(output), '.build-' + basename(output) + '-lock');
    const deadline = Date.now() + 10000;
    for (;;) {
        try {
            await mkdir(lock);
            break;
        } catch (error) {
            if (error.code !== 'EEXIST') throw error;
            if (Date.now() >= deadline) throw new Error('Timed out waiting to replace ' + output);
            await delay(20);
        }
    }
    try {
        await mkdir(output, { recursive: true });
        await rename(output, previous);
        try {
            await rename(stagedLib, output);
        } catch (error) {
            await rename(previous, output);
            throw error;
        }
    } finally {
        await rm(lock, { recursive: true, force: true });
    }
}

// Only the publisher builds this tree. Consumers install the finished JS and type declarations.
export async function buildRuntime(source = join(root, 'node_modules/werift'), output = join(root, 'lib')) {
    const [upstream, manifest, patch, facade] = await Promise.all([
        readFile(join(source, 'package.json'), 'utf8').then(JSON.parse),
        readFile(join(patches, 'manifest.json'), 'utf8').then(JSON.parse),
        readFile(join(patches, 'runtime.patch'), 'utf8'),
        readFile(join(patches, 'index.mjs'), 'utf8')
    ]);
    if (upstream.name + '@' + upstream.version !== manifest.baseVersion ||
        hash(patch) !== manifest.patchSha256 || hash(facade) !== manifest.facadeSha256) fail();
    const sources = new Map();
    for (const file of manifest.files) {
        const original = await readFile(join(source, 'lib', file.file), 'utf8');
        if (hash(original) !== file.before) fail();
        sources.set(file.file, original);
    }
    applyPatch(patch, sources);
    sources.set('index.mjs', facade);
    for (const file of manifest.files) {
        const patched = sources.get(file.file);
        if (hash(patched) !== file.after || hash(stripMap(patched)) !== file.prepared) fail();
    }

    const stage = await mkdtemp(join(dirname(output), '.build-'));
    const stagedLib = join(stage, 'lib');
    try {
        await cp(join(source, 'lib'), stagedLib, { recursive: true });
        for (const file of manifest.files) {
            const target = join(stagedLib, file.file);
            await writeFile(target, stripMap(sources.get(file.file)));
            await rm(target + '.map', { force: true });
        }
        await replaceBuild(stagedLib, output, join(stage, 'previous'));
    } finally {
        await rm(stage, { recursive: true, force: true });
    }
}

if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
    await buildRuntime();
}