import { promises as fs } from 'fs';
import path from 'path';

const projectRoot = process.cwd();
const excludedDirs = new Set(['vendor', 'storage', 'public', 'node_modules']);
const validExtensions = ['.php', '.vue'];

async function getFiles(dir) {
    const entries = await fs.readdir(dir, { withFileTypes: true });
    let files = [];
    for (const entry of entries) {
        const fullPath = path.join(dir, entry.name);
        if (excludedDirs.has(entry.name)) continue;
        if (entry.isDirectory()) {
            files = files.concat(await getFiles(fullPath));
        } else {
            if (validExtensions.some(ext => fullPath.endsWith(ext))) {
                files.push(fullPath);
            }
        }
    }
    return files;
}

function extractKeys(content) {
    const regex = /(?:__|trans)\(\s*['"]([^'"]+)['"]/g;
    const keys = [];
    let match;
    while ((match = regex.exec(content)) !== null) {
        keys.push(match[1]);
    }
    return keys;
}

async function main() {
    const translationPath = path.join(projectRoot, 'lang', 'en-US.json');
    let existing = {};
    try {
        existing = JSON.parse(await fs.readFile(translationPath, 'utf8'));
    } catch {
        existing = {};
    }

    const files = await getFiles(projectRoot);
    const usedKeys = new Set();
    for (const file of files) {
        const content = await fs.readFile(file, 'utf8');
        for (const key of extractKeys(content)) {
            usedKeys.add(key);
        }
    }

    let updated = false;
    for (const key of Array.from(usedKeys)) {
        if (!(key in existing)) {
            existing[key] = '';
            updated = true;
        }
    }

    if (updated) {
        await fs.writeFile(translationPath, JSON.stringify(existing, null, 4) + '\n');
        console.log('Updated', translationPath);
    } else {
        console.log('No missing keys found');
    }
}

main().catch(err => {
    console.error(err);
    process.exit(1);
});
