// @ts-check

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

const excludeRegexp = /\/node_modules|\/dump|\/.tmp|\/.next/;

function traverse(/** @type {String} - Directory path */ dir) {
    const files = fs.readdirSync(dir);

    if (dir.match(excludeRegexp)) return;

    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const filePath = path.resolve(dir, file);
        const fileStat = fs.statSync(filePath);

        if (fileStat.isDirectory()) {
            traverse(filePath);
            continue;
        }

        const fileMatch = file.match(/\.(jsx?)$/);

        if (fileMatch) {
            const fileContent = fs.readFileSync(filePath, "utf-8");
            if (fileContent.includes("@ts-check")) continue;
            fs.writeFileSync(
                filePath,
                "// @ts-check\n\n" + fileContent,
                "utf-8"
            );
        }
    }
}

traverse(process.cwd());