<?php

namespace App\Services;

use App\Config\KkoTaxonomy;

/**
 * KkoService — Query & Format KKO untuk AiService dan AtpRuleEngine
 *
 * Method utama:
 * - buildPromptKkoText() → format prompt utk AI
 * - getBloomLevel() → deteksi level Bloom dari verb
 * - validateTpVerb() → validasi KKO dlm deskripsi TP
 */
class KkoService
{
    protected string $group;

    public function __construct(string $group = 'Umum')
    {
        $this->group = $group;
    }

    /**
     * Set grup taxonomy
     */
    public function setGroup(string $group): void
    {
        $this->group = $group;
    }

    /**
     * Bangun teks KKO utk ditempel ke prompt AI
     * Output: 4 baris (kognitif dasar, lanjut, psikomotor, afektif)
     */
    public function buildPromptKkoText(?string $group = null): string
    {
        $g = $group ?? $this->group;
        $data = KkoTaxonomy::getForGroup($g);

        // Kognitif Dasar = C1 + C2
        $dasar = array_merge(
            $data['bloom']['C1']['kko'] ?? [],
            $data['bloom']['C2']['kko'] ?? []
        );
        $dasar = array_values(array_unique($dasar));

        // Kognitif Lanjut = C3 + C4 + C5 + C6
        $lanjut = array_merge(
            $data['bloom']['C3']['kko'] ?? [],
            $data['bloom']['C4']['kko'] ?? [],
            $data['bloom']['C5']['kko'] ?? [],
            $data['bloom']['C6']['kko'] ?? []
        );
        $lanjut = array_values(array_unique($lanjut));

        $psiko = $data['psikomotor']['kko'] ?? [];
        $afektif = $data['afektif']['kko'] ?? [];

        $text = "Kata Kerja Operasional (KKO) yang tersedia:\n";
        $text .= "   - Kognitif Dasar (C1-C2): " . implode(', ', $dasar) . "\n";
        $text .= "   - Kognitif Lanjut (C3-C6): " . implode(', ', $lanjut) . "\n";
        $text .= "   - Psikomotor: " . implode(', ', $psiko) . "\n";
        $text .= "   - Afektif/Ekspresi: " . implode(', ', $afektif) . "\n";

        return $text;
    }

    /**
     * Dapatkan level Bloom untuk satu kata kerja
     * Cari di semua level C1-C6, return level tertinggi jika ditemukan di multiple level
     * Return: int 1-6, atau null jika tidak ditemukan
     */
    public function getBloomLevel(string $verb, ?string $group = null): ?int
    {
        $g = $group ?? $this->group;
        $verb = strtolower(trim($verb));
        $verb = preg_replace('/[^a-z]/', '', $verb);
        if (empty($verb)) return null;

        $byLevel = KkoTaxonomy::getBloomKkoByLevel($g);
        $foundLevel = null;

        foreach (['C1', 'C2', 'C3', 'C4', 'C5', 'C6'] as $level) {
            if (in_array($verb, $byLevel[$level] ?? [])) {
                $foundLevel = (int) substr($level, 1); // 'C3' → 3
            }
        }

        return $foundLevel;
    }

    /**
     * Ekstrak kata kerja pertama dari kalimat dan dapatkan level Bloom-nya
     * Juga cek di 3 kata pertama jika kata pertama bukan KKO
     *
     * @return array ['valid' => bool, 'level' => int|null, 'verb' => string|null]
     */
    public function validateTpVerb(string $description, ?string $group = null): array
    {
        $g = $group ?? $this->group;
        $words = explode(' ', strtolower(trim($description)));
        if (empty($words)) {
            return ['valid' => false, 'level' => null, 'verb' => null];
        }

        // Cek kata pertama
        $firstWord = preg_replace('/[^a-z]/', '', $words[0]);
        $level = $this->getBloomLevel($firstWord, $g);
        if ($level !== null) {
            return ['valid' => true, 'level' => $level, 'verb' => $firstWord];
        }

        // Cek 3 kata pertama
        for ($i = 1; $i < min(count($words), 3); $i++) {
            $w = preg_replace('/[^a-z]/', '', $words[$i]);
            $level = $this->getBloomLevel($w, $g);
            if ($level !== null) {
                return ['valid' => true, 'level' => $level, 'verb' => $w];
            }
        }

        // Cek apakah salah satu kata adalah KKO psikomotor
        $psikoKko = KkoTaxonomy::getPsikomotorKko($g);
        foreach ($words as $w) {
            $clean = preg_replace('/[^a-z]/', '', $w);
            if (in_array($clean, $psikoKko)) {
                return ['valid' => true, 'level' => 3, 'verb' => $clean]; // Psikomotor ≈ C3
            }
        }

        // Cek afektif
        $afektifKko = KkoTaxonomy::getAfektifKko($g);
        foreach ($words as $w) {
            $clean = preg_replace('/[^a-z]/', '', $w);
            if (in_array($clean, $afektifKko)) {
                return ['valid' => true, 'level' => 2, 'verb' => $clean]; // Afektif ≈ C2
            }
        }

        return ['valid' => false, 'level' => null, 'verb' => $firstWord];
    }
}
