/**
 * ========================================================================
 * 路由参数与跳转中心化工具 (Backend / Web)
 * 
 * 核心目标：
 * 1. 统一所有页面的 URL 参数解析和跳转方法
 * 2. 标注参数的数据库来源，防止跨页面传错 ID
 * 3. 维护全局页面跳转关系图，供 AI 和开发者查阅
 * ========================================================================
 */

export interface AppRouterInstance {
  push: (url: string) => void | Promise<boolean>;
  replace?: (url: string) => void | Promise<boolean>;
  back?: () => void;
}

export interface ParamMeta {
  source_table: string;
  source_column: string;
  description: string;
}

function buildUrl(path: string, params: Record<string, string>): string {
  const sp = new URLSearchParams();
  Object.entries(params).forEach(([k, v]) => {
    if (v) sp.set(k, v);
  });
  const query = sp.toString();
  return query ? `${path}?${query}` : path;
}

// ================================================================
// B01 صفحة تسجيل دخول المدير — 无入参
// ================================================================
export const AdminLogin = {
  id: 'B01',
  path: '/adminlogin',
  paramsMeta: {} as Record<string, ParamMeta>,
  getParams: (_sp: URLSearchParams) => ({}),
  navigateTo: (router: AppRouterInstance) => router.push(AdminLogin.path)
}

// ================================================================
// B02 صفحة تسجيل المدير — 无入参
// ================================================================
export const AdminRegister = {
  id: 'B02',
  path: '/adminregister',
  paramsMeta: {} as Record<string, ParamMeta>,
  getParams: (_sp: URLSearchParams) => ({}),
  navigateTo: (router: AppRouterInstance) => router.push(AdminRegister.path)
}

// ================================================================
// B03 صفحة إدارة الطلبات — 入参: keyword, governorateName, driverName, orderType, status, page
// ================================================================
export const OrderManagement = {
  id: 'B03',
  path: '/ordermanagement',
  paramsMeta: {
    keyword: {
      source_table: '',
      source_column: '',
      description: 'البحث النصي العام (رقم الطلب، اسم الزبون، إلخ) - UI Virtual Param',
    },
    governorateName: {
      source_table: 'delivery_order',
      source_column: 'governorateName',
      description: 'تصفية حسب اسم المحافظة',
    },
    driverName: {
      source_table: 'delivery_order',
      source_column: 'driverName',
      description: 'تصفية حسب اسم السائق',
    },
    orderType: {
      source_table: 'delivery_order',
      source_column: 'orderType',
      description: 'تصفية حسب نوع الطلب',
    },
    status: {
      source_table: 'delivery_order',
      source_column: 'status',
      description: 'تصفية حسب حالة الطلب: PENDING/IN_PROGRESS/DELIVERED/CANCELLED',
    },
    page: {
      source_table: '',
      source_column: '',
      description: 'رقم الصفحة الحالية لترقيم النتائج - UI Virtual Param',
    },
  },
  getParams: (() => {
    const cache = new WeakMap<URLSearchParams, { keyword: string; governorateName: string; driverName: string; orderType: string; status: string; page: string; }>();
    return (sp: URLSearchParams) => {
      if (cache.has(sp)) return cache.get(sp)!;
      const result = {
        keyword: sp.get('keyword') || '',
        governorateName: sp.get('governorateName') || '',
        driverName: sp.get('driverName') || '',
        orderType: sp.get('orderType') || '',
        status: sp.get('status') || '',
        page: sp.get('page') || '',
      };
      cache.set(sp, result);
      return result;
    };
  })(),
  navigateToDefault: (router: AppRouterInstance) =>
    router.push(OrderManagement.path),
  navigateToWithStatus: (router: AppRouterInstance, params: { status: string }) =>
    router.push(buildUrl(OrderManagement.path, params)),
  navigateToWithSearch: (router: AppRouterInstance, params: { keyword: string; page: string }) =>
    router.push(buildUrl(OrderManagement.path, params)),
  navigateToWithFilters: (router: AppRouterInstance, params: { governorateName: string; driverName: string; status: string }) =>
    router.push(buildUrl(OrderManagement.path, params)),
}

// ================================================================
// B04 صفحة تفاصيل الطلب — 入参: orderId
// ================================================================
export const OrderDetail = {
  id: 'B04',
  path: '/orderdetail',
  paramsMeta: {
    orderId: {
      source_table: 'delivery_order',
      source_column: 'id',
      description: 'المعرف الفريد للطلب (Primary Key لجدول delivery_order)',
    },
  },
  getParams: (() => {
    const cache = new WeakMap<URLSearchParams, { orderId: string; }>();
    return (sp: URLSearchParams) => {
      if (cache.has(sp)) return cache.get(sp)!;
      const result = {
        orderId: sp.get('orderId') || '',
      };
      cache.set(sp, result);
      return result;
    };
  })(),
  navigateToDetail: (router: AppRouterInstance, params: { orderId: string }) =>
    router.push(buildUrl(OrderDetail.path, params)),
  navigateToDefault: (router: AppRouterInstance) =>
    router.push(OrderDetail.path),
}

// ================================================================
// B05 صفحة تعديل الطلب — 入参: id
// ================================================================
export const OrderEdit = {
  id: 'B05',
  path: '/orderedit',
  paramsMeta: {
    id: {
      source_table: 'delivery_order',
      source_column: 'id',
      description: 'المعرف الفريد للطلب المراد تعديله (Primary Key لجدول delivery_order)',
    },
  },
  getParams: (() => {
    const cache = new WeakMap<URLSearchParams, { id: string; }>();
    return (sp: URLSearchParams) => {
      if (cache.has(sp)) return cache.get(sp)!;
      const result = {
        id: sp.get('id') || '',
      };
      cache.set(sp, result);
      return result;
    };
  })(),
  navigateToDefault: (router: AppRouterInstance) =>
    router.push(OrderEdit.path),
  navigateToEdit: (router: AppRouterInstance, params: { id: string }) =>
    router.push(buildUrl(OrderEdit.path, params)),
}

// ================================================================
// B06 صفحة الإحصائيات والتحليلات الشهرية — 入参: startDate, endDate
// ================================================================
export const MonthlyAnalytics = {
  id: 'B06',
  path: '/monthlyanalytics',
  paramsMeta: {
    startDate: {
      source_table: 'delivery_order',
      source_column: 'createdAt',
      description: 'تاريخ بداية الفترة (يستخدم لتصفية createdAt) - YYYY-MM-DD',
    },
    endDate: {
      source_table: 'delivery_order',
      source_column: 'createdAt',
      description: 'تاريخ نهاية الفترة (يستخدم لتصفية createdAt) - YYYY-MM-DD',
    },
  },
  getParams: (() => {
    const cache = new WeakMap<URLSearchParams, { startDate: string; endDate: string; }>();
    return (sp: URLSearchParams) => {
      if (cache.has(sp)) return cache.get(sp)!;
      const result = {
        startDate: sp.get('startDate') || '',
        endDate: sp.get('endDate') || '',
      };
      cache.set(sp, result);
      return result;
    };
  })(),
  navigateToDefault: (router: AppRouterInstance) =>
    router.push(MonthlyAnalytics.path),
  navigateToWithDateRange: (router: AppRouterInstance, params: { startDate: string; endDate: string }) =>
    router.push(buildUrl(MonthlyAnalytics.path, params)),
}

// ================================================================
// B07 صفحة تصدير التقارير — 入参: reportType, startDate, endDate, governorateName, driverName, status
// ================================================================
export const ReportExport = {
  id: 'B07',
  path: '/reportexport',
  paramsMeta: {
    reportType: {
      source_table: '',
      source_column: '',
      description: 'نوع التقرير (ORDERS/DRIVERS/GOVERNORATES) - UI Virtual Param',
    },
    startDate: {
      source_table: 'delivery_order',
      source_column: 'createdAt',
      description: 'تاريخ بداية الفترة',
    },
    endDate: {
      source_table: 'delivery_order',
      source_column: 'createdAt',
      description: 'تاريخ نهاية الفترة',
    },
    governorateName: {
      source_table: 'delivery_order',
      source_column: 'governorateName',
      description: 'اسم المحافظة',
    },
    driverName: {
      source_table: 'delivery_order',
      source_column: 'driverName',
      description: 'اسم السائق',
    },
    status: {
      source_table: 'delivery_order',
      source_column: 'status',
      description: 'حالة الطلبات',
    },
  },
  getParams: (() => {
    const cache = new WeakMap<URLSearchParams, { reportType: string; startDate: string; endDate: string; governorateName: string; driverName: string; status: string; }>();
    return (sp: URLSearchParams) => {
      if (cache.has(sp)) return cache.get(sp)!;
      const result = {
        reportType: sp.get('reportType') || '',
        startDate: sp.get('startDate') || '',
        endDate: sp.get('endDate') || '',
        governorateName: sp.get('governorateName') || '',
        driverName: sp.get('driverName') || '',
        status: sp.get('status') || '',
      };
      cache.set(sp, result);
      return result;
    };
  })(),
  navigateToDefault: (router: AppRouterInstance) =>
    router.push(ReportExport.path),
  navigateToWithType: (router: AppRouterInstance, params: { reportType: string }) =>
    router.push(buildUrl(ReportExport.path, params)),
  navigateToWithDateRange: (router: AppRouterInstance, params: { startDate: string; endDate: string }) =>
    router.push(buildUrl(ReportExport.path, params)),
}

// ================================================================
// end
// ================================================================

export const BackendRoutes = {
  AdminLogin,
  AdminRegister,
  OrderManagement,
  OrderDetail,
  OrderEdit,
  MonthlyAnalytics,
  ReportExport,
};

export const NAVIGATION_MAP: Record<string, string[]> = {
  'B01': ['B03', 'B02'],
  'B02': ['B01'],
  'B03': ['B04', 'B05', 'B06', 'B07'],
  'B04': ['B05', 'B03'],
  'B05': ['B04', 'B03'],
  'B06': ['B07'],
  'B07': ['B06'],
};

export const PAGE_ID_MAP: Record<string, string> = {
  'B01': 'AdminLogin',
  'B02': 'AdminRegister',
  'B03': 'OrderManagement',
  'B04': 'OrderDetail',
  'B05': 'OrderEdit',
  'B06': 'MonthlyAnalytics',
  'B07': 'ReportExport',
};

/**
 * 传入页面 ID 或名称，从 route-params.ts 源文件中提取：
 *   1. 当前页面的 export const 代码块
 *   2. 当前页面所有跳转目标的 export const 代码块
 *
 * 返回的字符串可直接作为下游 AI prompt 的入参。
 * 支持 ID（F10）或名称（PaperCompose / papercompose），大小写不敏感。
 *
 * @example
 *   const text = getRouteContextText('F10', fileContent)
 *   const text = getRouteContextText('papercompose', fileContent)
 *   // 返回：PaperCompose + PaperList
 */
export function getRouteContextText(
  pageIdOrName: string,
  fileContent: string
): string {
  // 支持 ID（F10）或名称（PaperCompose），大小写不敏感
  let pageId = pageIdOrName
  let currentName = PAGE_ID_MAP[pageId]

  if (!currentName) {
    // 按名称查找（大小写不敏感）
    const lowerInput = pageIdOrName.toLowerCase()
    const entry = Object.entries(PAGE_ID_MAP).find(
      ([, name]) => name.toLowerCase() === lowerInput
    )
    if (entry) {
      pageId = entry[0]
      currentName = entry[1]
    }
  }

  if (!currentName) return `// 错误：未找到页面 ${pageIdOrName}`

  const targetIds = NAVIGATION_MAP[pageId] || []
  const targetNames = targetIds.map((id) => PAGE_ID_MAP[id]).filter(Boolean)

  // 按 "// ====" 分隔符切分文件为代码块
  const lines = fileContent.split('\n')
  const blocks: Record<string, string> = {}
  let currentBlock: string[] = []
  let currentBlockName = ''

  for (const line of lines) {
    if (line.startsWith('// ====')) {
      if (currentBlockName && currentBlock.length > 0) {
        blocks[currentBlockName] = currentBlock.join('\n').trim()
      }
      currentBlock = [line]
      currentBlockName = ''
      continue
    }
    const exportMatch = line.match(/^export const (\w+)\s*=/)
    if (exportMatch && !currentBlockName) {
      currentBlockName = exportMatch[1]
    }
    currentBlock.push(line)
  }
  if (currentBlockName && currentBlock.length > 0) {
    blocks[currentBlockName] = currentBlock.join('\n').trim()
  }

  function getBlock(name: string): string {
    return blocks[name] || `// 未找到 ${name} 的定义`
  }

  const parts: string[] = []
  parts.push('// ★★★ 当前页面 ★★★')
  parts.push(getBlock(currentName))
  if (targetNames.length > 0) {
    parts.push('// ★★★ 跳转目标页面（当前页面会 navigateTo 以下页面）★★★')
    for (const name of targetNames) {
      parts.push(getBlock(name))
    }
  }
  return parts.join('\n\n')
}
