<?php
/**
 * Arsenal Nexora - technical item catalog builder.
 * CLI only.
 *
 * Recommended:
 *   php includes/plugins/itemshop/tools_build_item_catalog.php /path/Items.xml /path/Item.txt
 *
 * Items.xml (Warehouse Editor) is authoritative for the warehouse footprint (X/Y)
 * and item capabilities. Item.txt is used as a cross-check and for server metadata.
 * Item.txt-only mode remains available for backwards compatibility.
 */
if(PHP_SAPI !== 'cli') { http_response_code(404); exit; }
if($argc < 2 || !is_file($argv[1]) || !is_readable($argv[1])) {
    fwrite(STDERR, "Uso: php ".$argv[0]." /ruta/Items.xml [/ruta/Item.txt]\n");
    exit(1);
}

$primary = $argv[1];
$secondary = ($argc >= 3 && is_file($argv[2]) && is_readable($argv[2])) ? $argv[2] : null;
$target = __DIR__.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'item-catalog.json';

function itemshopParseItemTxt($source) {
    $lines = file($source, FILE_IGNORE_NEW_LINES);
    if(!is_array($lines)) throw new RuntimeException('No se pudo leer Item.txt');
    $section = null;
    $items = array();
    $pattern = '/^\s*(\d+)\s+(\S+)\s+(-?\d+)\s+(\d+)\s+(\d+)\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)\s+"([^"]+)"/u';
    foreach($lines as $offset=>$line) {
        $trim = trim($line);
        if(preg_match('/^\d+$/', $trim)) {
            $value = (int)$trim;
            if($value >= 0 && $value <= 15) $section = $value;
            continue;
        }
        if(strtolower($trim) === 'end') { $section = null; continue; }
        if($section === null || $trim === '' || strpos($trim, '//') === 0) continue;
        if(!preg_match($pattern, $line, $m)) {
            throw new RuntimeException('Línea Item.txt no reconocida '.($offset+1).': '.$trim);
        }
        $row = array(
            's'=>$section,
            'i'=>(int)$m[1],
            'n'=>trim($m[9]),
            'w'=>(int)$m[4],
            'h'=>(int)$m[5],
            'slot'=>(string)$m[2],
            'skill'=>(int)$m[3],
            'serial'=>(int)$m[6],
            'option'=>(int)$m[7],
            'drop'=>(int)$m[8],
        );
        $items[$section.':'.$row['i']] = $row;
    }
    return $items;
}

function itemshopParseItemsXml($source) {
    $content = file_get_contents($source);
    if(!is_string($content) || $content === '') throw new RuntimeException('No se pudo leer Items.xml');
    if(!preg_match_all('/<Item\s+([^>]*?)\s*\/\s*>/u', $content, $matches)) {
        throw new RuntimeException('Items.xml no contiene ítems reconocibles');
    }
    $items = array();
    foreach($matches[1] as $attributesText) {
        $attrs = array();
        if(preg_match_all('/([A-Za-z0-9_]+)\s*=\s*"([^"]*)"/u', $attributesText, $pairs, PREG_SET_ORDER)) {
            foreach($pairs as $pair) $attrs[$pair[1]] = $pair[2];
        }
        if(!isset($attrs['Type'],$attrs['Index'],$attrs['Name'],$attrs['X'],$attrs['Y'])) continue;
        $section = (int)$attrs['Type'];
        $index = (int)$attrs['Index'];
        $name = trim((string)$attrs['Name']);
        $width = (int)$attrs['X'];
        $height = (int)$attrs['Y'];
        if($section < 0 || $section > 15 || $index < 0 || $name === '' || $width < 1 || $height < 1) continue;
        $items[$section.':'.$index] = array(
            's'=>$section,
            'i'=>$index,
            'n'=>$name,
            'w'=>$width,
            'h'=>$height,
            'excellent'=>isset($attrs['Excellent']) ? (int)$attrs['Excellent'] : 0,
            'level380'=>isset($attrs['Level380']) && strtolower($attrs['Level380']) === 'true' ? 1 : 0,
            'socket'=>isset($attrs['Socket']) && strtolower($attrs['Socket']) === 'true' ? 1 : 0,
        );
    }
    return $items;
}

try {
    $ext = strtolower(pathinfo($primary, PATHINFO_EXTENSION));
    $items = array();
    $sourceLabel = '';
    $sourceHashes = array();
    $conflicts = 0;

    if($ext === 'xml') {
        $xmlItems = itemshopParseItemsXml($primary);
        $txtItems = $secondary ? itemshopParseItemTxt($secondary) : array();
        foreach($xmlItems as $key=>$xmlRow) {
            $row = $xmlRow;
            if(isset($txtItems[$key])) {
                $txt = $txtItems[$key];
                $row['slot'] = $txt['slot'];
                $row['skill'] = $txt['skill'];
                $row['serial'] = $txt['serial'];
                $row['option'] = $txt['option'];
                $row['drop'] = $txt['drop'];
                $row['txt_n'] = $txt['n'];
                $row['txt_w'] = $txt['w'];
                $row['txt_h'] = $txt['h'];
                $row['dimension_conflict'] = ($txt['w'] !== $row['w'] || $txt['h'] !== $row['h']) ? 1 : 0;
                $row['name_conflict'] = (strcasecmp(trim($txt['n']), trim($row['n'])) !== 0) ? 1 : 0;
                if($row['dimension_conflict']) $conflicts++;
            } else {
                $row += array('slot'=>'','skill'=>0,'serial'=>0,'option'=>0,'drop'=>0,'dimension_conflict'=>0,'name_conflict'=>0);
            }
            $items[] = $row;
        }
        $sourceLabel = $secondary ? 'Items.xml · Warehouse Editor + Item.txt · MuServerPro' : 'Items.xml · Warehouse Editor';
        $sourceHashes['items_xml'] = hash_file('sha256', $primary);
        if($secondary) $sourceHashes['item_txt'] = hash_file('sha256', $secondary);
    } else {
        $txtItems = itemshopParseItemTxt($primary);
        $items = array_values($txtItems);
        foreach($items as &$row) {
            $row += array('excellent'=>0,'level380'=>0,'socket'=>0,'dimension_conflict'=>0,'name_conflict'=>0);
        }
        unset($row);
        $sourceLabel = 'Item.txt · MuServerPro';
        $sourceHashes['item_txt'] = hash_file('sha256', $primary);
    }

    usort($items, function($a,$b) {
        if($a['s'] === $b['s']) return $a['i'] <=> $b['i'];
        return $a['s'] <=> $b['s'];
    });

    $unsupported = 0;
    foreach($items as $item) if($item['i'] > 511) $unsupported++;
    $payload = array(
        'version'=>2,
        'source'=>$sourceLabel,
        'source_sha256'=>reset($sourceHashes),
        'source_hashes'=>$sourceHashes,
        'count'=>count($items),
        'dimension_conflicts'=>$conflicts,
        'items'=>$items,
    );
    $json = json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    if($json === false) throw new RuntimeException('No se pudo serializar el catálogo');
    if(!is_dir(dirname($target)) && !mkdir(dirname($target), 0755, true)) throw new RuntimeException('No se pudo crear data/');
    if(file_put_contents($target, $json, LOCK_EX) === false) throw new RuntimeException('No se pudo escribir '.$target);
    echo 'Catálogo generado: '.count($items).' ítems; '.(count($items)-$unsupported).' compatibles con Index 0-511; '.$unsupported.' fuera de rango; '.$conflicts." conflictos de dimensiones detectados.\n";
} catch(Throwable $e) {
    fwrite(STDERR, $e->getMessage()."\n");
    exit(2);
}
