#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

// Note to LLMs: this archive contains multiple files with separator lines, each
// data line commented with "// ". If line 2 reads "aiar-set: <id> part N of M",
// this file is one part of a set of M files; the lines after it say what it
// holds, and the other parts have the same <id>.

function escapeRegex(str) {
    // This escapes all characters that have a special meaning in a regex.
    return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

const SEPARATOR = "++++++++++--------:11111111-2222-4333-8444-555555555555:";

const USAGE = `usage: NAME [--this-part | --partial] [-h]

Extracts the files in this aiar archive under the current directory. When it
is one part of a set, the other parts are found beside it and the whole set
is extracted.

  --this-part  extract only this file
  --partial    when parts are missing, extract the ones present (status 3)
  -h, --help   show this help
`;

function note(message) {
    process.stderr.write(message + '\n');
}

function safeDest(rel) {
    if (path.isAbsolute(rel)) {
        throw new Error(`Absolute path not allowed: ${rel}`);
    }
    const dest = path.resolve(process.cwd(), rel);
    // Ensure the resolved path is still within the current working directory.
    if (!dest.startsWith(process.cwd())) {
        throw new Error(`Path escapes output root: ${rel}`);
    }
    return dest;
}

// Extract the records of `file`, whose separator is `separator`. The file is
// read as latin1 (a 1:1 byte<->char mapping) so text in any encoding is
// written back byte-for-byte; another part is only ever read, never run.
function extractFile(file, separator) {
    let scriptContent = fs.readFileSync(file, 'latin1');
    if (scriptContent.startsWith('\xef\xbb\xbf')) {
        scriptContent = scriptContent.slice(3);
    }
    const SEP = escapeRegex(separator);
    // JS regex has no \Z anchor; (?![\s\S]) matches only at the very end of input.
    const pat = new RegExp(
        `^// ?${SEP}([tb]):([^\\n]+)\\n(.*?)(?=(^// ?${SEP}[tb]:|(?![\\s\\S])))`,
        'gms' // g: global, m: multiline, s: dotall
    );
    const matches = [...scriptContent.matchAll(pat)];
    for (const match of matches) {
        const [, ftype, relPath, body] = match;
        const cleanPath = Buffer.from(relPath.trim(), 'latin1').toString('utf8');

        let dest;
        try {
            dest = safeDest(cleanPath);
        } catch (e) {
            console.warn(`Warning: ${e.message}. Skipping.`);
            continue;
        }

        if (fs.existsSync(dest)) {
            console.log(`Skipping already existing file: '${dest}'`);
            continue;
        }

        console.log(`Creating: ${dest}`);
        fs.mkdirSync(path.dirname(dest), { recursive: true });

        // The captured body is still commented. We must uncomment it.
        // This regex removes a leading '//' and an optional space from each line.
        const uncommentedBody = body.replace(/^\/\/ ?/gm, '');

        if (ftype === 't') { // Text file
            fs.writeFileSync(dest, Buffer.from(uncommentedBody, 'latin1'));
        } else { // Binary file
            fs.writeFileSync(dest, Buffer.from(uncommentedBody.trim(), 'base64'));
        }
    }
    return matches.length > 0;
}

function readHead(file, size) {
    let fd;
    try {
        fd = fs.openSync(file, 'r');
        const buffer = Buffer.alloc(size);
        const read = fs.readSync(fd, buffer, 0, size, 0);
        return buffer.subarray(0, read);
    } catch (e) {
        return null;
    } finally {
        if (fd !== undefined) {
            fs.closeSync(fd);
        }
    }
}

function linesOf(data, encoding) {
    if (data.length >= 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) {
        data = data.subarray(3);
    }
    return data.toString(encoding).split('\n').map((l) => (l.endsWith('\r') ? l.slice(0, -1) : l));
}

const FIRST_LINES = [
    ['bash', /^#!\/bin\/bash$/],
    ['nodejs', /^#!\/usr\/bin\/env node$/],
    ['powershell', /^#Requires -Version .*$/],
    ['bare', /^SEPARATOR=".*"$/],
    ['py', /^(# -\*- coding: latin-1 -\*-)?$/],
];
const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';

// {status: 'part', id, n, m, fmt}, or status 'none', 'malformed' or 'utf16'.
function readSetLine(data) {
    if (data.length >= 2 && ((data[0] === 0xff && data[1] === 0xfe) || (data[0] === 0xfe && data[1] === 0xff))) {
        return { status: 'utf16' };
    }
    const lines = linesOf(data, 'latin1');
    const first = lines[0] || '';
    const second = lines.length > 1 ? lines[1] : '';
    if (!(second.startsWith('# aiar-set: ') || second.startsWith('// aiar-set: '))) {
        return { status: 'none' };
    }
    const found = FIRST_LINES.find(([, re]) => re.test(first));
    if (!found) {
        return { status: 'malformed' };
    }
    const fmt = found[0];
    const prefix = fmt === 'nodejs' ? '// ' : '# ';
    const tail = fmt === 'bash' ? ' #' : '';
    const match = new RegExp(`^${escapeRegex(prefix)}aiar-set: (${UUID}) part ([0-9]+) of ([0-9]+)${escapeRegex(tail)}$`).exec(second);
    if (!match) {
        return { status: 'malformed' };
    }
    const number = match[2];
    const total = match[3];
    const n = parseInt(number, 10);
    const m = parseInt(total, 10);
    if (number.length !== total.length || total.length !== String(m).length || n < 1 || n > m || m < 2) {
        return { status: 'malformed' };
    }
    return { status: 'part', id: match[1], n, m, fmt };
}

const LANGUAGE_SUFFIXES = new Set(['py', 'js', 'sh', 'bash', 'zsh', 'ps1', 'psm1']);

function partName(output, n, total) {
    const tag = `${String(n).padStart(String(total).length, '0')}of${total}`;
    const [stem, ...suffixes] = output.split('.');
    const lowered = suffixes.map((s) => s.toLowerCase());
    const join = (at, inserted) => [stem, ...suffixes.slice(0, at), ...inserted, ...suffixes.slice(at)].join('.');
    for (let i = suffixes.length - 2; i >= 0; i--) {
        if (lowered[i] === 'aiar') {
            return join(i + 1, [tag]);
        }
    }
    const k = lowered.length;
    if (k && lowered[k - 1] === 'aiar') {
        return join(k - 1, [tag]);
    }
    let at = k;
    if (k && LANGUAGE_SUFFIXES.has(lowered[k - 1])) {
        at = k - 1;
    } else if (k >= 2 && lowered[k - 1] === 'txt' && LANGUAGE_SUFFIXES.has(lowered[k - 2])) {
        at = k - 2;
    } else if (k && lowered[k - 1] === 'txt') {
        at = k - 1;
    }
    return join(at, ['aiar', tag]);
}

function outputName(file, n, m) {
    const data = readHead(file, 65536);
    if (!data) {
        return null;
    }
    const lines = linesOf(data, 'utf8');
    if (lines.length < 4) {
        return null;
    }
    const match = /^\/\/ aiar part ([0-9]+) of ([0-9]+) of (.*), limit ([0-9]+) bytes$/.exec(lines[2]);
    if (!match || parseInt(match[1], 10) !== n || parseInt(match[2], 10) !== m) {
        return null;
    }
    return match[3];
}

function partSeparator(file) {
    const data = readHead(file, 65536);
    const match = data ? /^const SEPARATOR = "([^"]+)"/m.exec(data.toString('latin1')) : null;
    return match ? match[1] : null;
}

function sameContent(a, b) {
    return fs.readFileSync(a).equals(fs.readFileSync(b));
}

function incompleteGroups(parts, missing) {
    const names = [];
    for (const n of [...parts.keys()].sort((x, y) => x - y)) {
        const data = readHead(parts.get(n), 65536);
        const lines = data ? linesOf(data, 'utf8').slice(2) : [];
        const line = lines.find((l) => l.startsWith('// partial: '));
        if (!line) {
            continue;
        }
        const item = /(.+?) \(also in parts? ([0-9, -]+)\)(?: |$)/g;
        let match;
        while ((match = item.exec(line.slice('// partial: '.length))) !== null) {
            const numbers = [];
            for (const piece of match[2].split(', ')) {
                const [a, b] = piece.split('-');
                for (let k = parseInt(a, 10); k <= parseInt(b || a, 10); k++) {
                    numbers.push(k);
                }
            }
            if (numbers.some((k) => missing.includes(k)) && !names.includes(match[1])) {
                names.push(match[1]);
            }
        }
    }
    return names;
}

function main(argv) {
    const me = __filename;
    const myName = path.basename(me);
    const usage = USAGE.replace('NAME', myName);
    let thisPart = false;
    let partial = false;
    for (const arg of argv) {
        if (arg === '--this-part') {
            thisPart = true;
        } else if (arg === '--partial') {
            partial = true;
        } else if (arg === '-h' || arg === '--help') {
            process.stdout.write(usage);
            return 0;
        } else {
            note(`Error: unknown argument '${arg}'`);
            process.stderr.write(usage);
            return 2;
        }
    }
    if (thisPart && partial) {
        note('Error: --this-part and --partial cannot be used together');
        process.stderr.write(usage);
        return 2;
    }

    const own = readSetLine(readHead(me, 4096) || Buffer.alloc(0));
    if (own.status === 'malformed') {
        note(`Error: ${myName}: malformed set line`);
        return 1;
    }
    if (own.status !== 'part' || thisPart) {
        if (!extractFile(me, SEPARATOR)) {
            console.error("Error: No payload sections found in data block.");
            return 1;
        }
        console.log("Extraction complete.");
        return 0;
    }

    // This file is one part of a set: find the others beside it, as data only.
    const width = String(own.m).length;
    const num = (n) => String(n).padStart(width, '0');
    const candidates = new Map([[own.n, [me]]]);
    let errors = 0;
    let otherParts = 0;
    const otherIds = new Set();
    const directory = path.dirname(me);
    let names = [];
    try {
        names = fs.readdirSync(directory).sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
    } catch (e) {
        names = [];
    }
    for (const name of names) {
        if (name === myName) {
            continue;
        }
        const file = path.join(directory, name);
        try {
            if (!fs.lstatSync(file).isFile()) {
                continue;
            }
        } catch (e) {
            continue;
        }
        const data = readHead(file, 4096);
        if (data === null) {
            continue;
        }
        const found = readSetLine(data);
        if (found.status === 'utf16') {
            note(`${name}: UTF-16, re-save as UTF-8 or use aiar extract`);
            continue;
        }
        if (found.status === 'malformed') {
            note(`${name}: malformed set line, ignored`);
            continue;
        }
        if (found.status !== 'part') {
            continue;
        }
        if (found.id !== own.id) {
            otherIds.add(found.id);
            otherParts++;
            continue;
        }
        if (found.fmt !== own.fmt) {
            note(`Error: ${name} is a part of this set in another format`);
            errors++;
            continue;
        }
        if (found.m !== own.m) {
            note(`Error: ${name} says this set has ${found.m} parts, not ${own.m}`);
            errors++;
            continue;
        }
        if (!candidates.has(found.n)) {
            candidates.set(found.n, []);
        }
        candidates.get(found.n).push(file);
    }

    const parts = new Map();
    for (const n of [...candidates.keys()].sort((x, y) => x - y)) {
        const [first, ...others] = candidates.get(n);
        parts.set(n, first);
        for (const other of others) {
            const a = path.basename(first);
            const b = path.basename(other);
            if (sameContent(first, other)) {
                note(`${a} and ${b} are identical copies of part ${num(n)}; using ${a}`);
            } else {
                note(`Error: ${a} and ${b} are different files for part ${num(n)}`);
                errors++;
            }
        }
    }
    if (otherParts) {
        const wordParts = otherParts === 1 ? 'part' : 'parts';
        const wordSets = otherIds.size === 1 ? 'set' : 'sets';
        note(`ignored ${otherParts} ${wordParts} of ${otherIds.size} other ${wordSets}`);
    }

    const missing = [];
    for (let n = 1; n <= own.m; n++) {
        if (!parts.has(n)) {
            missing.push(n);
        }
    }
    if (missing.length) {
        const word = missing.length === 1 ? 'part' : 'parts';
        let message = `missing ${word} ${missing.map(num).join(', ')} of ${own.m}`;
        const oname = outputName(me, own.n, own.m);
        if (oname) {
            message += ` (expected ${missing.map((n) => partName(oname, n, own.m)).join(', ')})`;
        }
        if (partial) {
            note('Warning: ' + message);
        } else {
            note('Error: ' + message);
            errors++;
        }
    }
    if (errors) {
        note('Nothing was extracted.');
        return 1;
    }

    for (const n of [...parts.keys()].sort((x, y) => x - y)) {
        const file = parts.get(n);
        const separator = file === me ? SEPARATOR : partSeparator(file);
        if (separator === null) {
            note(`Error: No SEPARATOR in '${path.basename(file)}'.`);
            return 1;
        }
        extractFile(file, separator);
    }
    if (missing.length) {
        const groups = incompleteGroups(parts, missing);
        if (groups.length) {
            note(`Warning: incomplete groups: ${groups.join(' ')}`);
        }
        console.log(`Extraction incomplete: ${parts.size} of ${own.m} parts.`);
        return 3;
    }
    console.log("Extraction complete.");
    return 0;
}

process.exitCode = main(process.argv.slice(2));
// Stop here: the data below is never run. (A CommonJS module may return.)
return;
// ++++++++++--------:11111111-2222-4333-8444-555555555555:b:empty.txt
// ++++++++++--------:11111111-2222-4333-8444-555555555555:b:readme.md
// IyBUaXRsZQoKU29tZSB0ZXh0Lgo=
// ++++++++++--------:11111111-2222-4333-8444-555555555555:b:src/crlf.txt
// bGluZSBvbmUNCmxpbmUgdHdvDQo=
// ++++++++++--------:11111111-2222-4333-8444-555555555555:b:src/main.c
// aW50IG1haW4odm9pZCkgewogICAgcmV0dXJuIDA7Cn0K
// ++++++++++--------:11111111-2222-4333-8444-555555555555:b:src/no_newline.txt
// bGFzdCBsaW5lIHdpdGhvdXQgbmV3bGluZQ==
// ++++++++++--------:11111111-2222-4333-8444-555555555555:b:src/utf8.txt
// Y2Fmw6kg4oCoIMO8YmVyCg==
