<?php
declare(strict_types=1);

namespace App\Services\ZaloroxAI;

class ContentSuggestionService
{
    public function suggest(array $input): array
    {
        $type = ((string) ($input['type'] ?? 'mod')) === 'music' ? 'music' : 'mod';
        $title = trim((string) ($input['title'] ?? ''));
        $description = trim((string) ($input['description'] ?? ''));
        $category = trim((string) ($input['category'] ?? $input['game'] ?? ''));
        $fileName = trim((string) ($input['file_name'] ?? ''));
        $tags = (string) ($input['tags'] ?? '');
        $source = trim($title . ' ' . $description . ' ' . $category . ' ' . $fileName . ' ' . $tags);
        $normalized = $this->normalize($source);

        $warnings = [];
        if ($this->length($description) < 80) {
            $warnings[] = 'Bu aciklama cok kisa; kurulum, icerik ve surum notu eklemek kaliteyi artirir.';
        }
        if ($type === 'mod' && !preg_match('/\bFS\s?(17|19|22|25)\b/i', $source)) {
            $warnings[] = 'Baslikta oyun adi yok; FS25/FS22 gibi belirtmek aramada yardimci olur.';
        }
        if ($type === 'mod' && !str_contains($normalized, 'drive') && !str_contains($normalized, 'download') && !str_contains($normalized, 'indir')) {
            $warnings[] = 'Indirme linki veya kurulum kaynagi eklemelisin.';
        }
        if (!str_contains($normalized, 'cover') && !str_contains($normalized, 'kapak')) {
            $warnings[] = $type === 'music' ? 'Kapak gorseli icin kare 1:1 onerilir.' : 'Kapak gorseli 16:9 onerilir.';
        }

        $categorySuggestion = $this->categorySuggestion($type, $normalized);
        $summary = $this->summary($title, $description, $categorySuggestion, $type);
        $seo = $this->seoDescription($summary, $type);

        return [
            'category' => $categorySuggestion,
            'category_suggestion' => $categorySuggestion,
            'summary' => $summary,
            'seo_description' => $seo,
            'warnings' => array_values(array_unique($warnings)),
        ];
    }

    private function categorySuggestion(string $type, string $text): string
    {
        if ($type === 'music') {
            foreach ([
                'arabesk rap' => 'Arabesk Rap',
                'phonk' => 'Phonk',
                'drift' => 'Phonk',
                'trap' => 'Trap',
                'turku' => 'Turku',
                'karadeniz' => 'Karadeniz',
                'remix' => 'Remix',
                'oyun' => 'Oyun Muzigi',
                'game' => 'Oyun Muzigi',
                'rap' => 'Rap',
            ] as $needle => $category) {
                if (str_contains($text, $needle)) {
                    return $category;
                }
            }

            return 'Diger';
        }

        foreach ([
            'map' => 'Harita',
            'harita' => 'Harita',
            'tractor' => 'Traktor',
            'traktor' => 'Traktor',
            'trailer' => 'Romork',
            'romork' => 'Romork',
            'truck' => 'Kamyon',
            'kamyon' => 'Kamyon',
            'pack' => 'Paket',
            'paket' => 'Paket',
            'skin' => 'Kaplama',
            'texture' => 'Kaplama',
        ] as $needle => $category) {
            if (str_contains($text, $needle)) {
                return $category;
            }
        }

        return 'FS25 Mods';
    }

    private function summary(string $title, string $description, string $category, string $type): string
    {
        $base = trim(strip_tags($description));
        if ($base === '') {
            $base = $title !== '' ? $title : ($type === 'music' ? 'Yeni Zalorox muzik kaydi' : 'Yeni Zalorox mod kaydi');
        }

        $base = preg_replace('/\s+/', ' ', $base) ?: '';
        $base = $this->substr($base, 0, 150);

        return trim($base) . ($category !== '' ? ' [' . $category . ']' : '');
    }

    private function seoDescription(string $summary, string $type): string
    {
        $prefix = $type === 'music' ? 'Zalorox Music: ' : 'Zalorox mod rehberi: ';

        return $this->substr($prefix . $summary, 0, 155);
    }

    private function normalize(string $value): string
    {
        $value = function_exists('mb_strtolower') ? mb_strtolower($value, 'UTF-8') : strtolower($value);
        $value = strtr($value, [
            'ç' => 'c', 'ğ' => 'g', 'ı' => 'i', 'ö' => 'o', 'ş' => 's', 'ü' => 'u',
            'Ç' => 'c', 'Ğ' => 'g', 'İ' => 'i', 'Ö' => 'o', 'Ş' => 's', 'Ü' => 'u',
            'Ã§' => 'c', 'ÄŸ' => 'g', 'Ä±' => 'i', 'Ã¶' => 'o', 'ÅŸ' => 's', 'Ã¼' => 'u',
        ]);
        $value = preg_replace('/[^a-z0-9]+/u', ' ', $value) ?: '';

        return trim(preg_replace('/\s+/', ' ', $value) ?: '');
    }

    private function length(string $value): int
    {
        return function_exists('mb_strlen') ? mb_strlen($value, 'UTF-8') : strlen($value);
    }

    private function substr(string $value, int $start, int $length): string
    {
        return function_exists('mb_substr') ? mb_substr($value, $start, $length, 'UTF-8') : substr($value, $start, $length);
    }
}
