<?php

namespace App\Services;

use App\Models\ProductCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ProductCatalogThemeService
{
    /**
     * @param string $listingKey One of: main, books, tools_printables, tools_ilmonstery, reward
     */
    public function resolveListingTheme(
        string $listingKey,
        ?ProductCategory $selectedCategory,
        bool $isMontessoriPrints,
        bool $isReward
    ): array {
        $presets = config('product_catalog_themes.presets', []);

        if ($isReward) {
            $baseKey = 'reward';
        } elseif ($isMontessoriPrints) {
            $baseKey = 'prints';
        } elseif ($listingKey === 'books') {
            $baseKey = 'books';
        } elseif ($listingKey === 'tools_printables') {
            $baseKey = 'tools_printables';
        } elseif ($listingKey === 'tools_ilmonstery') {
            $baseKey = 'tools_ilmonstery';
        } elseif (! empty($selectedCategory)) {
            $baseKey = 'category';
        } else {
            $baseKey = 'main';
        }

        $preset = $presets[$baseKey]
            ?? $presets['main']
            ?? (array_values($presets)[0] ?? []);
        $theme = array_merge([], $preset);
        $theme['base_preset_key'] = $baseKey;

        $categoryId = optional($selectedCategory)->id;
        $personMap = config('product_catalog_themes.categories', []);
        if (! empty($categoryId) && ! empty($personMap[$categoryId])) {
            $pKey = $personMap[$categoryId];
            $personalities = config('product_catalog_themes.personalities', []);
            if (! empty($personalities[$pKey])) {
                $theme = array_replace_recursive($theme, $personalities[$pKey]);
                $theme['personality_key'] = $pKey;
            }
        }

        if (! empty($theme['hero_photo']) && is_string($theme['hero_photo'])) {
            $theme['hero_photo'] = trim($theme['hero_photo']);
        }

        return $theme;
    }

    /**
     * Log how the catalog hero theme was resolved (paths, file existence, asset URLs).
     * Enable with IMT_LOG_CATALOG_HERO=true in .env.
     */
    public function logListingThemeDiagnostics(Request $request, string $listingKey, array $theme): void
    {
        if (! config('product_catalog_themes.debug_log_listing_theme', false)) {
            return;
        }

        $heroRel = isset($theme['hero_photo']) && is_string($theme['hero_photo']) ? trim($theme['hero_photo']) : '';
        $decorRel = isset($theme['decor_asset']) && is_string($theme['decor_asset']) ? trim($theme['decor_asset']) : '';

        $heroResolved = '';
        if ($heroRel !== '' && preg_match('#^https?://#i', $heroRel)) {
            $heroResolved = $heroRel;
        } elseif ($heroRel !== '') {
            $heroResolved = asset($heroRel);
        }

        Log::info('imt.catalog_listing.hero_theme', [
            'listing_key' => $listingKey,
            'base_preset_key' => $theme['base_preset_key'] ?? null,
            'personality_key' => $theme['personality_key'] ?? null,
            'locale' => app()->getLocale(),
            'route' => $request->path(),
            'full_url' => $request->fullUrl(),
            'hero_photo_relative' => $heroRel ?: null,
            'hero_photo_public_disk_path' => $heroRel !== '' && ! preg_match('#^https?://#i', $heroRel) ? public_path($heroRel) : null,
            'hero_photo_disk_exists' => $heroRel !== '' && ! preg_match('#^https?://#i', $heroRel) ? is_file(public_path($heroRel)) : null,
            'hero_photo_asset_url' => $heroResolved ?: null,
            'decor_asset_relative' => $decorRel ?: null,
            'decor_asset_disk_exists' => $decorRel !== '' ? is_file(public_path($decorRel)) : null,
            'decor_asset_url' => $decorRel !== '' ? asset($decorRel) : null,
            'app_url_config' => config('app.url'),
            'asset_url_config' => config('app.asset_url'),
            'public_path_real' => realpath(public_path()),
        ]);
    }

    public function localizedHeroTitles(array &$theme, ?ProductCategory $selectedCategory, array $listingContext): void
    {
        $productsCount = (int) ($listingContext['products_count'] ?? 0);

        if (($theme['base_preset_key'] ?? '') === 'category' && ! empty($selectedCategory)) {
            $theme['hero_title'] = $selectedCategory->title;
            $theme['hero_subtitle'] = trans($theme['subtitle_fallback_trans'] ?? 'catalog.hero.category_fallback_subtitle', [
                'category' => $selectedCategory->title,
            ]);

            foreach ($theme['stats'] ?? [] as $i => $row) {
                if ($i === 0 && isset($theme['stats'][$i])) {
                    $theme['stats'][$i]['value'] = $productsCount > 0 ? $productsCount : ($theme['stats'][$i]['value'] ?? $productsCount);
                }
            }
            return;
        }

        $theme['hero_title'] = trans($theme['title_trans'] ?? '');
        $theme['hero_subtitle'] = trans($theme['subtitle_trans'] ?? '');

        if (($theme['base_preset_key'] ?? '') === 'main' && isset($theme['stats'][1])) {
            $theme['stats'][1]['value'] = $productsCount > 0 ? $productsCount : ($theme['stats'][1]['value'] ?? $productsCount);
        }
        if (($theme['base_preset_key'] ?? '') === 'prints' && isset($theme['stats'][0])) {
            $theme['stats'][0]['value'] = $productsCount > 0 ? $productsCount : ($theme['stats'][0]['value'] ?? $productsCount);
        }
        if (($theme['base_preset_key'] ?? '') === 'reward' && isset($theme['stats'][0])) {
            $theme['stats'][0]['value'] = $productsCount > 0 ? $productsCount : ($theme['stats'][0]['value'] ?? $productsCount);
        }
        if (($theme['base_preset_key'] ?? '') === 'books' && isset($theme['stats'][0])) {
            $theme['stats'][0]['value'] = $productsCount > 0 ? $productsCount : ($theme['stats'][0]['value'] ?? $productsCount);
        }

        if (in_array(($theme['base_preset_key'] ?? ''), ['tools_printables', 'tools_ilmonstery'], true) && isset($theme['stats'][0])) {
            $theme['stats'][0]['value'] = $productsCount > 0 ? $productsCount : ($theme['stats'][0]['value'] ?? $productsCount);
        }
    }
}
