import {SIDE_MENU_TYPE, SIDE_MENUS, STAFF_ROLE_TYPE} from "@/constants";
import axios from "axios";
import {clsx, type ClassValue} from "clsx";
import {twMerge} from "tailwind-merge";
interface ServiceInfo {
  uptime: number; // seconds
  pid: number;
  nodeVersion: string;
}

interface MemoryInfo {
  rss: number;
  heapUsed: number;
  heapTotal: number;
  external?: number;
}

interface CpuInfo {
  user: number; // microseconds
  system: number; // microseconds
}

interface EventLoopInfo {
  utilization: number; // 0..1
  active: number;
  idle: number;
}

interface SystemInfo {
  freeMemory: number;
  totalMemory: number;
}

export interface StatusResponse {
  service: ServiceInfo;
  memory: MemoryInfo;
  cpu: CpuInfo;
  eventLoop: EventLoopInfo;
  system: SystemInfo;
  timestamp: string;
}

// output type (UI-ready)
export interface FormattedSystemUI {
  uptime: string;
  pid: number;
  nodeVersion: string;

  heapUsed: string;
  heapTotal: string;
  rss: string;

  cpuUser: string;
  cpuSystem: string;

  eventLoopUtil: string;

  freeMemory: string;
  totalMemory: string;
}

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
export function getSideMenusByRole(
  menus: SIDE_MENU_TYPE[],
  role: STAFF_ROLE_TYPE
): SIDE_MENU_TYPE[] {
  return menus
    .map((menu) => {
      // بررسی دسترسی خود منوی اصلی
      const isMenuAllowed = !menu.roles || menu.roles.includes(role);

      // اگر submenu داشت، آیتم‌هاش رو فیلتر کن
      if (menu.sub?.items) {
        const allowedSubItems = menu.sub.items.filter(
          (item) => !item.roles || item.roles.includes(role)
        );

        // اگر نه خود منو مجازه، نه هیچ sub مجازه → حذف
        if (!isMenuAllowed && allowedSubItems.length === 0) {
          return null;
        }

        return {
          ...menu,
          sub: {
            ...menu.sub,
            items: allowedSubItems,
          },
        };
      }

      // منوی بدون sub
      return isMenuAllowed ? menu : null;
    })
    .filter(Boolean) as SIDE_MENU_TYPE[];
}
export function formatSystemForUI(data: StatusResponse): FormattedSystemUI {
  // uptime
  const uptimeSec = data.service.uptime;
  const h = Math.floor(uptimeSec / 3600);
  const m = Math.floor((uptimeSec % 3600) / 60);
  const uptime = h > 0 ? `${h}h ${m}m` : `${m}m`;

  // memory formatter
  const formatMem = (bytes: number): string => {
    const gb = bytes / 1024 / 1024 / 1024;
    if (gb >= 1) return `${gb.toFixed(2)} GB`;
    return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
  };

  return {
    uptime,
    pid: data.service.pid,
    nodeVersion: data.service.nodeVersion,

    heapUsed: formatMem(data.memory.heapUsed),
    heapTotal: formatMem(data.memory.heapTotal),
    rss: formatMem(data.memory.rss),

    cpuUser: `${(data.cpu.user / 1000).toFixed(1)} ms`,
    cpuSystem: `${(data.cpu.system / 1000).toFixed(1)} ms`,

    eventLoopUtil: `${(data.eventLoop.utilization * 100).toFixed(2)}%`,

    freeMemory: formatMem(data.system.freeMemory),
    totalMemory: formatMem(data.system.totalMemory),
  };
}
// تابع کمکی برای تبدیل مسیر dynamic به regex
export function pathToRegex(path: string) {
  // تبدیل /patients/edit/:id به /^\/patients\/edit\/[^/]+$/
  const regexString = "^" + path.replace(/:[^/]+/g, "[^/]+") + "$";
  return new RegExp(regexString);
}

// گرفتن تمام مسیرها همراه با roles
export function getAllPathsWithRoles() {
  const paths: {path: string; roles: STAFF_ROLE_TYPE[]}[] = [];

  SIDE_MENUS.forEach((menu) => {
    // مسیر منوی اصلی
    if (menu.href && menu.href !== "#") {
      paths.push({path: menu.href, roles: menu.roles!});
    }

    // مسیرهای sub items
    if (menu.sub?.items) {
      menu.sub.items.forEach((item) => {
        if (item.href && item.href !== "#") {
          paths.push({path: item.href, roles: item.roles!});
        }
      });
    }
  });

  return paths;
}

export function handleAxiosError(error: unknown) {
  if (axios.isAxiosError(error)) {
    // اینجا می‌دونیم که خطا از axios است
    return error.response?.data?.error?.message;
  } else {
    return "Unexpected error";
  }
}
