<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;

class ItemIconService
{
    private const CACHE_KEY = 'item_icon_mapping';
    private const CACHE_DURATION = 86400; // 24 hours

    /**
     * Get the icon filename for a given vnum
     */
    public static function getIconForVnum(int $vnum): ?string
    {
        $mapping = self::getMapping();

        if (isset($mapping[$vnum])) {
            return $mapping[$vnum];
        }

        return null;
    }

    /**
     * Get the full icon mapping array
     */
    public static function getMapping(): array
    {
        return Cache::remember(self::CACHE_KEY, self::CACHE_DURATION, function () {
            return self::parseItemList();
        });
    }

    /**
     * Parse the item_list.txt file and build the mapping
     */
    private static function parseItemList(): array
    {
        $mapping = [];

        // Get the base path relative to this file (app/Services -> go up 2 levels)
        $basePath = dirname(__DIR__, 2);

        // Try multiple possible locations - data folder first (baked into Docker image)
        $paths = [
            $basePath . '/data/item_list.txt',
            $basePath . '/storage/app/item_list.txt',
            '/app/data/item_list.txt',
            '/app/storage/app/item_list.txt',
        ];

        $path = null;
        foreach ($paths as $p) {
            if (file_exists($p)) {
                $path = $p;
                break;
            }
        }

        if ($path === null) {
            return $mapping;
        }

        $content = file_get_contents($path);
        if ($content === false) {
            return $mapping;
        }

        // Normalize line endings
        $content = str_replace("\r\n", "\n", $content);
        $content = str_replace("\r", "\n", $content);

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

        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line)) {
                continue;
            }

            // Split by tab
            $parts = preg_split('/\t+/', $line);
            if (count($parts) >= 2) {
                $vnum = (int) $parts[0];
                $icon = trim($parts[1]);

                // Remove .png extension and any directory path
                $icon = pathinfo($icon, PATHINFO_FILENAME);

                if ($vnum > 0 && !empty($icon)) {
                    $mapping[$vnum] = $icon;
                }
            }
        }

        return $mapping;
    }

    /**
     * Clear the cached mapping
     */
    public static function clearCache(): void
    {
        Cache::forget(self::CACHE_KEY);
    }
}
