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

const target = path.resolve(process.argv[2] || "app/js/app.js");
const source = fs.readFileSync(target, "utf8");
const newline = source.includes("\r\n") ? "\r\n" : "\n";
const lines = source.split(/\r?\n/);
const functions = [];

for (let start = 0; start < lines.length; start += 1) {
    const match = lines[start].match(/^    function\s+([A-Za-z0-9_]+)\s*\(/);
    if (!match) continue;

    let end = start + 1;
    while (end < lines.length && !/^    }$/.test(lines[end])) end += 1;
    if (end >= lines.length) throw new Error(`Could not find end of ${match[1]} at line ${start + 1}`);
    functions.push({ name: match[1], start, end });
    start = end;
}

const lastByName = new Map();
for (const fn of functions) lastByName.set(fn.name, fn);
const remove = new Set();
const removedNames = [];

for (const fn of functions) {
    if (lastByName.get(fn.name) === fn) continue;
    removedNames.push(fn.name);
    for (let line = fn.start; line <= fn.end; line += 1) remove.add(line);
    if (lines[fn.end + 1] === "") remove.add(fn.end + 1);
}

if (remove.size) {
    fs.writeFileSync(target, lines.filter((_, index) => !remove.has(index)).join(newline), "utf8");
}

process.stdout.write(`Removed ${removedNames.length} shadowed functions: ${removedNames.join(", ")}\n`);
