import type { AstroIntegration } from "astro";
import { mkdir, access, constants, copyFile, rename } from "node:fs/promises";

const locales = ["de"];

export default function configureI18n(): AstroIntegration {
    return {
        name: "astro-i18n-renamer",
        hooks: {
            "astro:build:done": async ({pages, dir, logger, routes}) => {
                for (const page of pages) {
                    const [locale, ...rest] = page.pathname.split("/");
                    if (locales.includes(locale)) {
                        const path = rest.join("/");
                        const oldPath = `${dir.pathname}${page.pathname}`;
                        const newPath = `${dir.pathname}${path}`;
                        try {
                            await access(cutPrefix(newPath), constants.R_OK | constants.W_OK);
                        } catch (e) {
                            await mkdir(cutPrefix(newPath), {recursive: true});
                        }

                        await copyFile(`${cutPrefix(oldPath)}index.html`, `${cutPrefix(newPath)}index.html.${locale}`);
                        logger.info(`Copied ${oldPath}index.html to ${newPath}index.html.${locale}`);
                    } else {
                        const oldPath = cutPrefix(`${dir.pathname}${page.pathname}`);
                        await rename(`${oldPath}index.html`, `${oldPath}index.html.en`);
                    }
                }
            }
        }
    };
}

function cutPrefix(path: string): string {
    return process.platform === "win32" ? path.substring(1) : path;
}