<?php
/**
 * Regenerate attachment metadata (all registered sub-sizes + width/height +
 * srcset data) for a chunk of attachment IDs. Reads IDs from the file named in
 * the BW_CHUNK constant. Tiny stdout so it doesn't balloon the gateway.
 *
 * Called (one physical line — eval splits on newlines):
 *   wp eval 'define("BW_CHUNK","/var/www/html/wp-content/_imp_hero/chunk_00.txt"); require "/var/www/html/wp-content/_imp_hero/regen_hero.php";'
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }
if ( ! defined( 'BW_CHUNK' ) || ! is_file( BW_CHUNK ) ) { echo "NO CHUNK\n"; return; }

require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
@set_time_limit( 0 );

$ids = array_filter( array_map( 'intval', file( BW_CHUNK, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ) ) );
$ok = 0; $fail = 0; $maxw = 0; $errs = array();

foreach ( $ids as $id ) {
	$file = get_attached_file( $id );
	if ( ! $file || ! file_exists( $file ) ) { $fail++; $errs[] = "$id:nofile"; continue; }
	$meta = wp_generate_attachment_metadata( $id, $file );
	if ( is_wp_error( $meta ) || empty( $meta['width'] ) ) { $fail++; $errs[] = "$id:genfail"; continue; }
	wp_update_attachment_metadata( $id, $meta );
	$ok++;
	if ( $meta['width'] > $maxw ) { $maxw = $meta['width']; }
	// free memory between large images
	unset( $meta );
	if ( function_exists( 'wp_cache_flush' ) && ( $ok % 50 === 0 ) ) { wp_cache_flush(); }
}
echo "CHUNK ok=$ok fail=$fail maxw=$maxw";
if ( $errs ) { echo " errs=" . implode( ',', array_slice( $errs, 0, 10 ) ); }
echo "\n";
