function category_template($template) {
    // 1. 快速失败:非分类页面直接返回
    if (!is_category()) {
        return $template;
    }

    $category = get_queried_object();

    // 2. 基础校验:确保对象有效且属于 category 分类法
    if (!$category || is_wp_error($category) || empty($category->term_id) || $category->taxonomy !== 'category') {
        return $template;
    }

    $parent = (int) $category->parent;
    $iteration_limit = 10; // 安全阈值:防止死循环或过深层级
    $count = 0;

    // 3. 向上遍历寻找最顶层父分类
    while ($parent !== 0 && $count < $iteration_limit) {
        $parent_cat = get_category($parent);

        // 防御性编程:防止获取失败导致死循环
        if (!$parent_cat || is_wp_error($parent_cat) || empty($parent_cat->term_id)) {
            break;
        }

        $category = $parent_cat;
        $parent = (int) $category->parent;
        
        $count++;
    }

    // 4. 异常监控
    if ($count >= $iteration_limit) {
        error_log(sprintf('[CM Smart Assistant] Warning: Category hierarchy limit reached (%d levels) for term_id %d. Check for circular references.', $iteration_limit, $category->term_id));
    }

    // 5. 构建模板查找列表
    $templates = array(
        "category-{$category->slug}.php",
        "category-{$category->term_id}.php",
        "category.php",
    );

    // 6. 定位模板并安全返回
    $located = locate_template($templates);
    
    return $located ? $located : $template;
}
add_filter('category_template', 'category_template');