<?php
/**
 * Arsenal Nexora - Render cache builder (CLI only)
 * Normaliza item_images WEBP a thumbnails transparentes 160x160.
 * Requiere GD con soporte WebP. No se ejecuta durante requests web.
 */
if(PHP_SAPI !== 'cli') {
    fwrite(STDERR, "CLI only.\n");
    exit(1);
}
if(!extension_loaded('gd') || !function_exists('imagecreatefromwebp') || !function_exists('imagewebp')) {
    fwrite(STDERR, "GD con soporte WebP es requerido.\n");
    exit(1);
}

$source = isset($argv[1]) ? rtrim($argv[1], "\\/") : dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'nexoraves6custom'.DIRECTORY_SEPARATOR.'img'.DIRECTORY_SEPARATOR.'item_images';
$target = isset($argv[2]) ? rtrim($argv[2], "\\/") : dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'nexoraves6custom'.DIRECTORY_SEPARATOR.'img'.DIRECTORY_SEPARATOR.'itemshop-renders-v1';

if(!is_dir($source)) {
    fwrite(STDERR, "No existe el directorio fuente: {$source}\n");
    exit(1);
}
if(!is_dir($target) && !mkdir($target, 0775, true)) {
    fwrite(STDERR, "No se pudo crear el directorio destino: {$target}\n");
    exit(1);
}

const TARGET_SIZE = 160;
const MAX_CONTENT_W = 106;
const MAX_CONTENT_H = 116;
const MAX_UPSCALE = 2.0;
const WEBP_QUALITY = 82;

function transparentCanvas($w, $h) {
    $img = imagecreatetruecolor($w, $h);
    imagealphablending($img, false);
    imagesavealpha($img, true);
    $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
    imagefill($img, 0, 0, $transparent);
    return $img;
}

function alphaBounds($img) {
    $w = imagesx($img);
    $h = imagesy($img);
    $minX = $w; $minY = $h; $maxX = -1; $maxY = -1;
    for($y=0; $y<$h; $y++) {
        for($x=0; $x<$w; $x++) {
            $rgba = imagecolorat($img, $x, $y);
            $alpha = ($rgba >> 24) & 0x7F;
            if($alpha < 127) {
                if($x < $minX) $minX = $x;
                if($x > $maxX) $maxX = $x;
                if($y < $minY) $minY = $y;
                if($y > $maxY) $maxY = $y;
            }
        }
    }
    if($maxX < $minX || $maxY < $minY) return null;
    return array($minX, $minY, $maxX-$minX+1, $maxY-$minY+1);
}

$generated = 0;
$skipped = 0;
$bytes = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS));
foreach($iterator as $file) {
    if(!$file->isFile() || strtolower($file->getExtension()) !== 'webp') continue;
    $src = $file->getPathname();
    $img = @imagecreatefromwebp($src);
    if(!$img) { $skipped++; continue; }
    imagesavealpha($img, true);
    $bounds = alphaBounds($img);
    if($bounds === null) { imagedestroy($img); $skipped++; continue; }
    list($sx,$sy,$sw,$sh) = $bounds;
    $scale = min(MAX_CONTENT_W/$sw, MAX_CONTENT_H/$sh, MAX_UPSCALE);
    $dw = max(1, (int)round($sw*$scale));
    $dh = max(1, (int)round($sh*$scale));

    $scaled = transparentCanvas($dw, $dh);
    if($scale > 1.0) {
        imagecopyresized($scaled, $img, 0,0,$sx,$sy,$dw,$dh,$sw,$sh);
    } else {
        imagecopyresampled($scaled, $img, 0,0,$sx,$sy,$dw,$dh,$sw,$sh);
    }
    imagedestroy($img);

    $canvas = transparentCanvas(TARGET_SIZE, TARGET_SIZE);
    $dx = (int)floor((TARGET_SIZE-$dw)/2);
    $dy = max(8, (int)floor((142-$dh)/2));
    imagecopy($canvas, $scaled, $dx, $dy, 0, 0, $dw, $dh);
    imagedestroy($scaled);

    $relative = substr($src, strlen($source)+1);
    $relative = preg_replace('/\.webp$/i', '.webp', $relative);
    $out = $target.DIRECTORY_SEPARATOR.$relative;
    $dir = dirname($out);
    if(!is_dir($dir) && !mkdir($dir, 0775, true)) {
        imagedestroy($canvas);
        fwrite(STDERR, "No se pudo crear: {$dir}\n");
        exit(1);
    }
    if(!imagewebp($canvas, $out, WEBP_QUALITY)) {
        imagedestroy($canvas);
        fwrite(STDERR, "No se pudo escribir: {$out}\n");
        exit(1);
    }
    imagedestroy($canvas);
    $generated++;
    $bytes += (int)@filesize($out);
}

fwrite(STDOUT, "Render cache generado: {$generated} archivos; omitidos: {$skipped}; bytes: {$bytes}\n");
exit(0);
