import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const IMAGES_DIR = path.resolve(__dirname, '../public/images');
const DATA_FILE = path.resolve(__dirname, '../lib/data.ts');
const GALLERY_FILE = path.resolve(__dirname, '../lib/gallery_data.ts');

function slugify(text) {
    return text.toString().toLowerCase()
        .replace(/ç/g, 'c')
        .replace(/ğ/g, 'g')
        .replace(/ı/g, 'i')
        .replace(/ö/g, 'o')
        .replace(/ş/g, 's')
        .replace(/ü/g, 'u')
        .replace(/[^a-z0-9.]/g, '-')
        .replace(/\-\-+/g, '-')
        .replace(/^-+/, '')
        .replace(/-+$/, '');
}

function processDirectory(dir, mapping = []) {
    const entries = fs.readdirSync(dir, { withFileTypes: true });

    for (const entry of entries) {
        const oldPath = path.join(dir, entry.name);
        let newName = slugify(path.parse(entry.name).name);
        if (entry.isFile()) {
            newName += path.extname(entry.name).toLowerCase();
        }
        
        const newPath = path.join(dir, newName);

        if (entry.isDirectory()) {
            // Recurse first before renaming directory
            processDirectory(oldPath, mapping);
        }

        if (oldPath !== newPath) {
            console.log(`Renaming: ${oldPath} -> ${newPath}`);
            fs.renameSync(oldPath, newPath);
            
            const oldRelative = path.relative(IMAGES_DIR, oldPath).replace(/\\/g, '/');
            const newRelative = path.relative(IMAGES_DIR, newPath).replace(/\\/g, '/');
            mapping.push({ old: oldRelative, new: newRelative });
        }
    }
    return mapping;
}

console.log("Starting rename process...");
// First rename files inside directories, then rename directories
// To do this safely, we should gather all files, then directories, and rename bottom-up.
function getAllPaths(dir) {
    let results = [];
    const entries = fs.readdirSync(dir, { withFileTypes: true });
    for (const entry of entries) {
        const fullPath = path.join(dir, entry.name);
        if (entry.isDirectory()) {
            results = results.concat(getAllPaths(fullPath));
        }
        results.push({ path: fullPath, isDir: entry.isDirectory(), name: entry.name });
    }
    return results;
}

const allPaths = getAllPaths(IMAGES_DIR).sort((a, b) => b.path.length - a.path.length); // Bottom up
const mapping = [];

for (const item of allPaths) {
    const oldPath = item.path;
    const dir = path.dirname(oldPath);
    let newName = slugify(path.parse(item.name).name);
    if (!item.isDir) {
        newName += path.extname(item.name).toLowerCase();
    }
    const newPath = path.join(dir, newName);

    if (oldPath !== newPath) {
        fs.renameSync(oldPath, newPath);
        console.log(`Renamed: ${item.name} -> ${newName}`);
        
        // We will just do a global replace in files using slugify on the strings later
        // It's easier than keeping track of complex path mapping.
    }
}
console.log("Renaming done.");
