<?php

namespace App\Helpers;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

class TextDataHelper
{
    private static $textData = null;
    private static $isLoaded = false;

    /**
     * Get localized text by string ID
     *
     * @param string $stringId
     * @param string $fallback
     * @return string
     */
    public static function getText($stringId, $fallback = '')
    {
        self::loadTextData();

        return self::$textData[$stringId] ?? $fallback;
    }

    /**
     * Check if a string ID exists
     *
     * @param string $stringId
     * @return bool
     */
    public static function hasText($stringId)
    {
        self::loadTextData();

        return isset(self::$textData[$stringId]);
    }

    /**
     * Search for text entries by pattern
     *
     * @param string $pattern
     * @param int $limit
     * @return array
     */
    public static function search($pattern, $limit = 10)
    {
        self::loadTextData();

        $results = [];
        $count = 0;

        foreach (self::$textData as $stringId => $text) {
            if (stripos($stringId, $pattern) !== false || stripos($text, $pattern) !== false) {
                $results[$stringId] = $text;
                $count++;

                if ($count >= $limit) {
                    break;
                }
            }
        }

        return $results;
    }

    /**
     * Get statistics about loaded textdata
     *
     * @return array
     */
    public static function getStats()
    {
        self::loadTextData();

        return [
            'total_entries' => count(self::$textData),
            'loaded' => self::$isLoaded,
            'memory_usage' => memory_get_usage(true)
        ];
    }

    /**
     * Load all textdata into memory
     */
    protected static function loadTextData()
    {
        if (self::$isLoaded) {
            return;
        }

        self::$textData = [];

        // Load both files directly without caching
        $equipData = self::loadTextDataFile('textdata_equip&skill.txt');
        $objectData = self::loadTextDataFile('textdata_object.txt');

        // Combine both arrays
        self::$textData = array_merge($equipData, $objectData);
        self::$isLoaded = true;

        Log::info('TextData loaded: ' . count(self::$textData) . ' entries');
    }

    /**
     * Load and parse a textdata file
     * Format: 1\tSTRING_ID\tText
     *
     * @param string $fileName
     * @return array
     */
    protected static function loadTextDataFile($fileName)
    {
        $filePath = public_path("assets/textdata/{$fileName}");

        if (!File::exists($filePath)) {
            Log::warning("TextData file not found: {$filePath}");
            return [];
        }

        try {
            // Read file and handle UTF-16LE encoding
            $content = file_get_contents($filePath);

            // Check for UTF-16LE BOM and convert to UTF-8
            if (substr($content, 0, 2) === "\xFF\xFE") {
                $content = mb_convert_encoding($content, 'UTF-8', 'UTF-16LE');
            }

            $lines = explode("\n", $content);
            $textData = [];

            foreach ($lines as $lineNumber => $line) {
                $line = trim($line);

                // Skip empty lines and comments
                if (empty($line) || str_starts_with($line, '//')) {
                    continue;
                }

                // Parse line using fixed format: 1\tSTRING_ID\t...\t...\t...\t...\t...\t...\t...\tNAME_TEXT
                $parts = explode("\t", $line);

                if (count($parts) >= 10) {
                    $stringId = trim($parts[1]);
                    $text = trim($parts[9]); // Get text from column 9 (index 9) - the last column

                    // Clean text to avoid encoding issues
                    $text = self::cleanText($text);

                    if (!empty($stringId) && !empty($text)) {
                        $textData[$stringId] = $text;
                    }
                }
            }

            Log::info("Loaded {$fileName}: " . count($textData) . " entries");
            return $textData;

        } catch (\Exception $e) {
            Log::error("Error loading TextData file {$fileName}: " . $e->getMessage());
            return [];
        }
    }

    /**
     * Clear loaded textdata (force reload on next access)
     *
     * @return void
     */
    public static function clearCache()
    {
        self::$textData = null;
        self::$isLoaded = false;
        Log::info('TextData cleared from memory');
    }

    /**
     * Clean text to avoid encoding issues
     */
    private static function cleanText(string $text): string
    {
        // Return empty if text is empty
        if (empty($text)) {
            return '';
        }

        // Remove or replace invalid UTF-8 characters
        $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');

        // Remove control characters except tab and newline
        $text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text);

        // Check if text is valid UTF-8
        if (!mb_check_encoding($text, 'UTF-8')) {
            return '';
        }

        // Return cleaned text only if it's not empty after cleaning
        $cleaned = trim($text);
        return $cleaned;
    }    /**
     * Preload textdata into memory
     *
     * @return void
     */
    public static function preload()
    {
        self::loadTextData();
        Log::info('TextData preloaded with ' . count(self::$textData) . ' entries');
    }

    /**
     * Get all textdata entries (for debugging)
     *
     * @param int $limit
     * @return array
     */
    public static function getAllTextData($limit = null)
    {
        self::loadTextData();

        if ($limit) {
            return array_slice(self::$textData, 0, $limit, true);
        }

        return self::$textData;
    }
}
