// import { fileURLToPath } from "url";
import fs from "fs-extra";
import path from "path";

const envs = import.meta.env;
let sassEnvVariables = "";

for (let e in envs) {
  if (/VITE_/i.test(e)) {
    sassEnvVariables += `$${e}: "${import.meta.env[e]}";`;
  }
}

// dynamically importing styles.
const buildName = import.meta.env.VITE_BUILD_NAME;
let mainStyle = `~/assets/common/scss/${buildName}-styles.scss`;

if (buildName == "haditha")
  mainStyle = `~/systems/${buildName.substring(
    0,
    buildName.length - 1
  )}_ui/assets/${buildName}/scss/${buildName}.css`;

export default defineNuxtConfig({
  hooks: {
    "build:before": () => {
      if (buildName == "haditha") {
        const sourceDir = path.resolve(
          __dirname,
          `systems/${buildName.substring(
            0,
            buildName.length - 1
          )}_ui/assets/${buildName}/images`
        ); // Source folder (e.g., assets/images)
        const targetDir = path.resolve(__dirname, `public/img/${buildName}`); // Target folder (e.g., public/images)

        // Ensure the target directory exists
        fs.ensureDirSync(targetDir);

        // Copy files from source to target
        fs.copySync(sourceDir, targetDir);

        console.log("Files copied successfully!");
      }
    },

    "pages:extend"(pages) {
      // Add custom routes
      pages.push(
        {
          name: "search",
          path: "/search",
          file: "~/systems/search_ui/pages/search/index.vue",
        },
        {
          name: "searchNavigation",
          path: "/search/lists",
          file: "~/systems/search_ui/pages/search/lists.vue",
        },
        {
          name: "searchChart",
          path: "/search/charts",
          file: "~/systems/search_ui/pages/search/charts.vue",
        },
        {
          name: "showEntity",
          path: "/search/:key/:id/show",
          file: "~/systems/search_ui/pages/search/(show)/[key]/[id]/index.vue",
        },
        {
          name: "navigationView",
          path: "/search/:key/:id/list",
          file: "~/systems/search_ui/pages/search/(show)/[key]/[id]/index.vue",
        },
        {
          name: "entityResearch",
          path: "/search/:key/:id/research",
          file: "~/systems/search_ui/pages/search/(show)/[key]/[id]/index.vue",
        },
        {
          name: "entityResearch",
          path: "/search/:key/:id/detail",
          file: "~/systems/search_ui/pages/search/(show)/[key]/[id]/index.vue",
        },
        // --------------------- start: Research routes ---------------------
        {
          name: "myResearches",
          path: "/research/research-home",
          file: "~/systems/research_ui/pages/index.vue",
        },
        {
          name: "TermPage",
          path: "/research/research-term",
          file: "~/systems/research_ui/pages/TermPage.vue",
        },
        // --------------------- end: Research routes ---------------------

        // --------------------- start: haditha routes ---------------------
        {
          name: "haditha",
          path: "/haditha",
          file: "~/systems/hadith_ui/pages/haditha/index.vue",
        },
        {
          name: "hadithaSearch",
          path: "/haditha/search",
          file: "~/systems/hadith_ui/pages/haditha/search/index.vue",
        },
        {
          name: "hadithaChatBot",
          path: "/haditha/chat-bot",
          file: "~/systems/hadith_ui/pages/haditha/chat-bot.vue",
        },
        {
          name: "hadithaFavorites",
          path: "/haditha/favorites",
          file: "~/systems/hadith_ui/pages/haditha/favorites/index.vue",
        },
        {
          name: "hadithaLibrary",
          path: "/haditha/library",
          file: "~/systems/hadith_ui/pages/haditha/library/index.vue",
        },
        {
          name: "hadithaLibraryShow",
          path: "/haditha/library/:id/:slug?",
          file: "~/systems/hadith_ui/pages/haditha/library/[id]/[slug]/index.vue",
        },
        {
          name: "hadithaAbout",
          path: "/haditha/about-us",
          file: "~/systems/hadith_ui/pages/haditha/public-pages/about-us.vue",
        },
        {
          name: "hadithaContact",
          path: "/haditha/contact-us",
          file: "~/systems/hadith_ui/pages/haditha/public-pages/ContactUs.vue",
        },
        {
          name: "hadithaRules",
          path: "/haditha/rules",
          file: "~/systems/hadith_ui/pages/haditha/public-pages/rules.vue",
        },
        {
          name: "hadithaLogin",
          path: "/haditha/login",
          file: "~/systems/hadith_ui/pages/haditha/login.vue",
        }

        // --------------------- end: haditha routes ---------------------
      );
    },
  },

  nitro: {
    compressPublicAssets: true,
    prerender: {
      routes: ["/haditha/about-us", "/haditha/contact"], // Pre-render these routes
    },
  },

  colorMode: {
    preference: "light",
  },
  compatibilityDate: "2024-04-03",
  components: [
    {
      path: "~/components/global",
      extensions: ["vue"],
      pathPrefix: false,
    },

    // "vue-tree-list",
    // "vuejs-paginate",
  ],
  devtools: {
    enabled: process.env.NODE_ENV === "development",
    vscode: {
      reuseExistingServer: true,
    },
  },

  features: {
    inlineStyles: false,
  },
  debug: false,
  // Modules and plugins
  modules: [
    "@pinia/nuxt",
    "pinia-plugin-persistedstate/nuxt",
    "@nuxtjs/i18n",
    "floating-vue/nuxt",
    "nuxt-echarts",
    "@vueuse/nuxt",
    "@nuxt/ui",
    "@nuxtjs/color-mode",
    "@nuxt/test-utils/module",
    // 'nuxt-delay-hydration',
    "@nuxt/image",
    // "@nuxtjs/supabase",
  ],
  icon: {
    customCollections: [
      {
        prefix: "haditha",
        dir: `./systems/${buildName.substring(
          0,
          buildName.length - 1
        )}_ui/assets/${buildName}/font-icons`,
      },
    ],
  },
  // ui: {
  //   prefix: 'Nuxt', //Use the prefix option to change the prefix of the components.    Default: U
  //   fonts: false, // Use the fonts option to enable or disable the @nuxt/fonts module.    Default: true
  //   colorMode: false, // Use the colorMode option to enable or disable the @nuxt/color-mode module.     Default: true
  //   theme: {
  //     colors: ['primary', 'error'] // Use the theme.colors option to define the dynamic color aliases used to generate components theme.
  //   },
  // },
  // delayHydration: {
  //   // enables nuxt-delay-hydration in dev mode for testing
  //   debug: process.env.NODE_ENV === 'development',
  //   mode: 'init'
  // },
  // image: {
  //   provider: "ipx",
  //   quality: 100,
  // },
  i18n: {
    vueI18n: "./i18n.config.ts", // if you are using custom path, default
  },
  pinia: {
    // storesDirs: ["./stores/**", "./custom-folder/stores/**"],
    storesDirs: ["./stores/**"],
  },
  plugins: [
    { src: "~/plugins/api.ts", mode: "client" },
    { src: "~/plugins/vuelidate.ts", mode: "client" },
    { src: "~/plugins/bootstrap.client.ts", mode: "client" },
    { src: "~/plugins/vueJalaliMoment.ts", mode: "client" },
    { src: "~/plugins/vueDraggable.client.ts", ssr: false, mode: "client" },
    { src: "~/plugins/vue3TreeVue.client.ts" },
    { src: "~/plugins/vue3PersianDateTimePicker.client.ts" },
    // { src: "~/plugins/vueTreeList.client.ts", ssr: false, mode: "client" },
    // { src: "~/plugins/vueJsTree.ts" },
  ],

  runtimeConfig: {
    public: {
      ...import.meta.env,
    },
  },
  css: [
    mainStyle,
    // "vue3-persian-datetime-picker/src/picker/assets/scss/style.scss",
  ],
  alias: {
    "@apis": "~/apis",
    "@components": "~/components",
    "@configs": "~/configs",
    "@extensions": "~/extensions",
    "@json": "~/json",
    "@layouts": "~/layouts",
    "@mixins": "~/mixins",
    "@plugins": "~/plugins",
    "@services": "~/services",
    "@stores": "~/stores",
    "@types": "~/types",
    "@utils": "~/utils",
    "@manuals": "~/manuals",
    "@pages": "~/pages",
    "@search": "~/systems/search_ui",
    "@research": "~/systems/research_ui",
    "@haditha": "~/systems/hadith_ui",
  },
  vite: {
    resolve: {},
    // optimizeDeps: {
    //   exclude: ["vue-demi"],
    // },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: sassEnvVariables,
          sassOptions: { quietDeps: true },
        },
        sass: {
          sassOptions: {
            quietDeps: true,
            silenceDeprecations: ["legacy-js-api"],
          },
        },
      },
    },
  },
  build: {
    analyze: true,
    // transpile: ["echarts", "resize-detector", "echarts-wordcloud"],
  },
  // postcss: {
  //   plugins: {
  //     tailwindcss: {},
  //     autoprefixer: {},
  //   },
  // },

  // "~": "/<srcDir>",
  // "@": "/<srcDir>",

  // Pages (pages/)
  // Components (components/)
  // Layouts (layouts/)
  // Store (store/)
  // Middleware (middleware/)
  // Plugins (plugins/)
  // And more...

  // "~~": "/<rootDir>",
  // "@@": "/<rootDir>",

  // package.json
  // nuxt.config.js
  // node_modules/
  // And more...

  // "assets": "/<srcDir>/assets",
  // "public": "/<srcDir>/public"
  // @ and ~ which point to the srcDir,
  // @@ and ~~ which point to the rootDir

  // runtimeConfig in Nuxt represents an advanced configuration layer,
  //  allowing you to define settings that are accessible on both the
  // client and server sides

  // https://nuxt.com/docs/api/configuration/nuxt-config

  // console.info("import.meta.env.VITE_APP_NAME", import.meta.env.VITE_APP_NAME);
  // console.info("import.meta.env.VITE_APP_NAME", import.meta.env.VITE_APP_NAME);
  // console.info("import.meta.env.VITE_TINY_PASSWORD", import.meta.env.VITE_TINY_PASSWORD);
  // console.info("import.meta.env.NODE_ENV", import.meta.env);
  // console.info("monir", monir);
  // console.info("monir", monir.parsed.VITE_APP_NAME);

  // let monir = require("dotenv").config({ path: ".env.monir" });
  // require("dotenv").config({ path: `.env.${import.meta.env.NODE_ENV}` });

  // routeRules: {
  //   "/admin/**": { ssr: false },
  //   "/api/**": { cors: true },
  //   "/_nuxt/**": { headers: { "cache-control": "s-maxage=0" } },
  // },
  // ssr: true,
  // app: {
  // pageTransition: { name: "page", mode: "out-in" },
  // layoutTransition: { name: "layout", mode: "out-in" },
  // },
  // alias: {
  // images: fileURLToPath(new URL("@@/components", import.meta.url)),
  // style: fileURLToPath(new URL("@@/composables", import.meta.url)),
  // data: fileURLToPath(new URL("@@/layouts", import.meta.url)),

  // apis: fileURLToPath(new URL("@@/apis", import.meta.url)),
  // assets: fileURLToPath(new URL("@@/assets", import.meta.url)),
  // components: fileURLToPath(new URL("@@/components", import.meta.url)),
  // json: fileURLToPath(new URL("@@/json", import.meta.url)),
  // layouts: fileURLToPath(new URL("@@/layouts", import.meta.url)),
  // mixins: fileURLToPath(new URL("@@/mixins", import.meta.url)),
  // pages: fileURLToPath(new URL("@@/pages", import.meta.url)),
  // plugins: fileURLToPath(new URL("@@/plugins", import.meta.url)),
  // services: fileURLToPath(new URL("@@/services", import.meta.url)),
  // store: fileURLToPath(new URL("@@/store", import.meta.url)),
  // routes: fileURLToPath(new URL("@@/routes", import.meta.url)),
  // directives: fileURLToPath(new URL("@@/directives", import.meta.url)),
  // utilities: fileURLToPath(new URL("@@/utilities", import.meta.url)),
  // extensions: fileURLToPath(new URL("@@/extensions", import.meta.url)),
  // publicPages: fileURLToPath(
  //   new URL("@@/modules/public-pages", import.meta.url)
  // ),

  // search: fileURLToPath(new URL("@@/systems/search", import.meta.url)),
  // tahrir: fileURLToPath(new URL("@@/systems/tahrir", import.meta.url)),
  // list: fileURLToPath(new URL("@@/systems/list", import.meta.url)),
  // jahat: fileURLToPath(new URL("@@/systems/jahat", import.meta.url)),
  // chat: fileURLToPath(new URL("@@/systems/chat", import.meta.url)),
  // borhan: fileURLToPath(new URL("@@/systems/borhan", import.meta.url)),
  // reports: fileURLToPath(new URL("@@/systems/reports", import.meta.url)),
  // lms: fileURLToPath(new URL("@@/systems/lms", import.meta.url)),
  // thiqat: fileURLToPath(new URL("@@/systems/thiqat", import.meta.url)),
  // task: fileURLToPath(new URL("@@/systems/task", import.meta.url)),
  // aiTools: fileURLToPath(new URL("@@/systems/ai-tools", import.meta.url)),

  // admin: fileURLToPath(new URL("@@/panels/admin", import.meta.url)),
  // user: fileURLToPath(new URL("@@/panels/user", import.meta.url)),
  // majles: fileURLToPath(new URL("@@/panels/majles", import.meta.url)),

  // research: fileURLToPath(new URL("@@/modules/research", import.meta.url)),
  // favorites: fileURLToPath(new URL("@@/modules/favorite", import.meta.url)),
  // permission: fileURLToPath(
  //   new URL("@@/modules/permissions", import.meta.url)
  // ),
  // dataSetting: fileURLToPath(
  //   new URL("@@/modules/data-setting", import.meta.url)
  // ),
  // notifications: fileURLToPath(
  //   new URL("@@/modules/notifications", import.meta.url)
  // ),
  // entity: fileURLToPath(new URL("@@/modules/entity", import.meta.url)),

  // settings: fileURLToPath(new URL("@@/modules/settings", import.meta.url)),
  // dashboard: fileURLToPath(new URL("@@/modules/dashboard", import.meta.url)),
  // forms: fileURLToPath(new URL("@@/modules/forms", import.meta.url)),
  // rezome: fileURLToPath(new URL("@@/modules/rezome", import.meta.url)),
  // },

  // build: {
  // transpile: ["echarts", "resize-detector", "echarts-wordcloud"],
  // },
  // typescript: {
  //   typeCheck: true, // Enable type checking at build time
  //   strict: true, // Enable strict type checks (default is true)
  // },
  // sourcemap: {
  //   server: true,
  //   client: true,
  // },
});

// typescript: {
//   typeCheck: true, // Enable type checking at build time
//   strict: true, // Enable strict type checks
//   tsConfig: {
//     compilerOptions: {
//       // Extend or override compiler options here
//     },
//   },
// },
// console.log(import.meta.env.VARIABLE_NAME);
// console.log(this.$config.public.VARIABLE_NAME);
// const runtimeConfig :" useRuntimeConfig()",
// console.log(runtimeConfig.apiSecret)
// console.log(runtimeConfig.public.apiBase)

// Resolve ~, ~~, @ and @@ aliases located within layers with respect to their layer source and root directories.