import { defineStore } from 'pinia';
import { RouteRecordRaw } from 'vue-router';
import api from '../api';
import Layout from '../views/Layout.vue';
import { useUserStore } from './user';

// Dynamic import map matching backend "component" string
const modules = import.meta.glob('../views/**/*.vue');

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [] as RouteRecordRaw[],
    addRoutes: [] as RouteRecordRaw[],
    sidebarMenus: [] as any[], // For rendering sidebar
  }),
  actions: {
    async generateRoutes() {
      try {
        console.log('Generating routes...');
        const res: any = await api.get('/getRouters');
        console.log('API response:', res);
        
        // Debug: Print available modules
        console.log('Available view modules:', Object.keys(modules));

        // Save permissions to user store
        const userStore = useUserStore();
        // Mark roles as initialized to prevent infinite loop in router guard
        if (userStore.roles.length === 0) {
            userStore.roles = ['ROLE_USER']; // Default role or fetch from backend
        }
        
        if (res.permissions) {
            userStore.setPermissions(res.permissions);
        }

        if (!res.menus) {
            console.warn('No menus returned from backend');
            return [];
        }

        // Mock Menus removed as we use backend menus
        // const mockMenus = ...


        // Use backend menus
        const sdata = JSON.parse(JSON.stringify(res.menus));
        const rdata = JSON.parse(JSON.stringify(res.menus));
        
        const sidebarMenus = filterSidebarMenus(sdata);
        const rewriteRoutes = filterAsyncRoutes(rdata, false, true);
        console.log('Rewrite routes:', rewriteRoutes);

        // Add Device Live View Route manually (Hidden)
        // Using lazy loading for the component
        rewriteRoutes.push({
            path: '/monitor/device-live/:id',
            name: 'DeviceLive',
            component: () => import('../views/monitor/DeviceLive.vue'),
            meta: { title: '设备实时数据', hidden: true, activeMenu: '/resource/import' },
            children: [] 
        } as any);

        // Add 404 catch-all route at the end
        rewriteRoutes.push({
            path: '/:pathMatch(.*)*',
            redirect: '/login',
            hidden: true
        });
        
        this.sidebarMenus = sidebarMenus;
        this.addRoutes = rewriteRoutes;
        // Don't modify router directly here, return them to be added
        return rewriteRoutes;
      } catch (error) {
        console.error('Failed to generate routes', error);
        return [];
      }
    }
  }
});

// Helper to filter sidebar menus 
// Exclude Type 'F' (buttons) and Visible '1' (hidden)
function filterSidebarMenus(menus: any[]) {
  return menus.filter(route => {
    if (route.type === 'F' || route.visible === '1') {
      return false;
    }
    if (route.children && route.children.length) {
      route.children = filterSidebarMenus(route.children);
      // If after filtering children, no children remain and it's a directory (M), maybe hide it? 
      // Or keep it if it can be clicked.
      // For now, keep it.
    }
    return true;
  });
}

// Helper to convert backend response to vue-router routes
function filterAsyncRoutes(routes: any[], _lastRouter: any = false, type = false) {
  return routes.filter(route => {
    // Drop buttons or invalid nodes early to avoid invalid vue-router records
    if (route.type === 'F' || !route.path) {
      return false;
    }

    if (type && route.children) {
      route.children = filterAsyncRoutes(route.children, route, type);
    }

    if (route.component) {
      // Layout component handling
      if (route.component === 'Layout') {
        route.component = Layout;
      } else {
        // Dynamic component loading
        // Backend returns "system/UserRole", we need "../views/system/UserRole.vue"
        const componentPath = `../views/${route.component}.vue`;
        
        // Normalize path for check (replace backslashes just in case)
        const normalizedPath = componentPath.replace(/\\/g, '/');

        if (modules[normalizedPath]) {
          route.component = modules[normalizedPath];
        } else {
          // Try fuzzy match to handle case sensitivity or path issues
          const targetSuffix = `/views/${route.component}.vue`.toLowerCase();
          const matchedKey = Object.keys(modules).find(key => 
             key.toLowerCase().endsWith(targetSuffix) || key.toLowerCase().endsWith(targetSuffix.replace('..', ''))
          );
          
          if (matchedKey) {
             console.log(`Fuzzy matched component: ${route.component} -> ${matchedKey}`);
             route.component = modules[matchedKey];
          } else {
             console.warn(`Component not found: ${componentPath} (normalized: ${normalizedPath})`);
             console.warn('Available modules:', Object.keys(modules));
             // Don't fail completely, use a placeholder to allow debugging
             route.component = { template: '<div style="padding: 20px; color: red;">Component not found: ' + route.component + '</div>' };
          }
        }
      }
    } else if (!route.children || route.children.length === 0) {
      // Leaf nodes must have a component, otherwise they break navigation
      return false;
    }

    // Recursive processing cleanup
    if (route.children != null && route.children.length) {
      // keep children
    } else {
      delete route['children'];
      delete route['redirect'];
    }
    return true;
  });
}
