import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import html from '@rollup/plugin-html';
import { glob } from 'glob';
import path from 'path';
import fs from 'fs';
import fse from 'fs-extra';

/**
 * Devuelve archivos de componentes
 */
function getComponentFiles(type) {
    return glob.sync(`vendor/koneko/**/resources/${type}/**/*.${type === 'js' ? 'js' : 'scss'}`);
}

/**
 * Devuelve solo archivos reales, omitiendo carpetas
 */
/**
 * Devuelve solo archivos válidos, omitiendo carpetas, .map, .php, test y node_modules
 */
function GetFilesArray(query) {
    return glob.sync(query, {
        ignore: [
            '**/node_modules/**',
            '**/test/**',
            '**/*.map',
            '**/*.php',
            '**/*.md',
            '**/*.txt',
            '**/*.json',
            '**/*.config.js',
            '**/index.php'
        ]
    }).filter(file => {
        try {
            const stats = fs.statSync(file);
            return stats.isFile();
        } catch (e) {
            return false;
        }
    });
}

/**
 * Asignación especial para librerías globales
 */
function libsWindowAssignment() {
    return {
        name: 'libsWindowAssignment',
        transform(src, id) {
            if (id.includes('jkanban.js')) {
                return src.replace('this.jKanban', 'window.jKanban');
            } else if (id.includes('vfs_fonts')) {
                return src.replaceAll('this.pdfMake', 'window.pdfMake');
            }
        }
    };
}

/**
 * Copiar fuentes de Tabler
 */
function copyTablerFonts() {
    const from = 'node_modules/@tabler/icons-webfont/dist/fonts';
    const to   = 'public/build/webfonts/tabler';

    return {
        name: 'copy-tabler-fonts',
        buildStart() {
            fse.ensureDirSync(to);
            fse.copySync(from, to, { overwrite: true });
            console.log('📁 Tabler fonts copied to:', to);
        }
    };
}

/**
 * Copiar fuentes de Font Awesome
 */
function copyFontAwesomeFonts() {
    const from = 'node_modules/@fortawesome/fontawesome-free/webfonts';
    const to   = 'public/build/webfonts';

    return {
        name: 'copy-fontawesome-fonts',
        buildStart() {
            fse.ensureDirSync(to);
            fse.copySync(from, to, { overwrite: true });
            console.log('📁 Font Awesome fonts copied to:', to);
        }
    };
}

/**
 * Asset groups de componentes
 */
const vendorJsFiles  = GetFilesArray('vendor/koneko/laravel-vuexy-admin/resources/assets/vendor/js/*.js');
const libsJsFiles    = GetFilesArray('vendor/koneko/laravel-vuexy-admin/resources/assets/vendor/libs/**/*.js');
const coreScssFiles  = GetFilesArray('vendor/koneko/laravel-vuexy-admin/resources/assets/vendor/scss/**/!(_)*.scss');
const libsScssFiles  = GetFilesArray('vendor/koneko/laravel-vuexy-admin/resources/assets/vendor/libs/**/!(_)*.scss');
const libsCssFiles   = GetFilesArray('vendor/koneko/laravel-vuexy-admin/resources/assets/vendor/libs/**/*.css');
const fontsScssFiles = GetFilesArray('vendor/koneko/laravel-vuexy-admin/resources/assets/vendor/fonts/!(_)*.scss');
const assetsJsFiles  = GetFilesArray('vendor/koneko/**/resources/assets/js/**/*.js');
const pageJsFiles    = getComponentFiles('js');
const pageScssFiles  = getComponentFiles('scss');

// assets de layouts tipo website, ecommerce, landing...
const layoutJSFiles   = GetFilesArray('vendor/koneko/laravel-vuexy-*-layout-*/resources/assets/**/js/**/*.js');
const layoutSCSSFiles = GetFilesArray('vendor/koneko/laravel-vuexy-*-layout-*/resources/assets/**/scss/**/*.scss');
const layoutCSSFiles  = GetFilesArray('vendor/koneko/laravel-vuexy-*-layout-*/resources/assets/**/css/**/*.css');
const layoutVendorJSFiles   = GetFilesArray('vendor/koneko/laravel-vuexy-*-layout-*/resources/assets/**/vendor/**/*.js');
const layoutVendorSCSSFiles = GetFilesArray('vendor/koneko/laravel-vuexy-*-layout-*/resources/assets/**/vendor/**/*.scss');
const layoutVendorCSSFiles  = GetFilesArray('vendor/koneko/laravel-vuexy-*-layout-*/resources/assets/**/vendor/**/*.css');
const layoutFontsScssFiles = GetFilesArray('vendor/koneko/laravel-vuexy-*-layout-*/resources/assets/**/vendor/fonts/!(_)*.scss');

const inputs = {
    admin: [
        'vendor/koneko/laravel-vuexy-admin/resources/assets/css/demo.css',
        ...vendorJsFiles,
        ...libsJsFiles,
        ...coreScssFiles,
        ...libsScssFiles,
        ...libsCssFiles,
        ...fontsScssFiles,
        ...assetsJsFiles,
        ...pageJsFiles,
        ...pageScssFiles
    ],
    frontend: [
        ...layoutJSFiles,
        ...layoutSCSSFiles,
        ...layoutCSSFiles,
        ...layoutVendorJSFiles,
        ...layoutVendorSCSSFiles,
        ...layoutVendorCSSFiles,
        ...layoutFontsScssFiles
    ]
};

/**
 * Aplanar entradas
 */
const flatInputs = Object.entries(inputs).reduce((acc, [group, paths]) => {
    paths.forEach((p, i) => {
        acc[`${group}-${i}`] = p;
    });
    return acc;
}, {});

/**
 * Configuración final
 */
export default defineConfig({
    plugins: [
        laravel({
            input: Object.values(flatInputs),
            refresh: [
                'resources/views/**',
                'resources/frontend/views/**',
                'vendor/koneko/**/resources/views/**',
            ]
        }),
        html(),
        libsWindowAssignment(),
        copyTablerFonts(),
        copyFontAwesomeFonts(),
    ],
    resolve: {
        alias: {
            '@vuexy-admin': path.resolve(__dirname, 'vendor/koneko/laravel-vuexy-admin/resources/'),
            '@vuexy-contacts': path.resolve(__dirname, 'vendor/koneko/laravel-vuexy-contacts/resources/'),
            '@vuexy-store-manager': path.resolve(__dirname, 'vendor/koneko/laravel-vuexy-store-manager/resources/'),
            '@vuevy-warehouse': path.resolve(__dirname, 'vendor/koneko/laravel-vuevy-warehouse/resources/'),
            '@vuevy-asset-management': path.resolve(__dirname, 'vendor/koneko/laravel-vuevy-asset-management/resources/'),
        },
    },
    build: {
        emptyOutDir: true,
        rollupOptions: {
            external: ['axios']
        }
    },
    server: {
        cors: true,
        hmr: {
            host: '127.0.0.1',
        },
        fs: {
            allow: ['..'],
        },
        watch: {
            ignored: [
                '**/node_modules/**',
                '**/storage/**',
                '**/public/**'
            ],
        }
    },
});
