<?php
declare(strict_types=1);

namespace App\Command;

use Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use App\Service\EmbeddingsClient;

class EmbedFaqsCommand extends Command
{
    public function execute(Arguments $args, ConsoleIo $io)
    {
        $Faqs = $this->fetchTable('Faqs');
        $client = new EmbeddingsClient();

        $rows = $Faqs->find()
            ->select(['id','question','answer','embedding_json'])
            ->enableHydration(false)->all();

        $done = 0;
        foreach ($rows as $r) {
            if (!empty($r['embedding_json'])) { continue; } // skip already embedded

            $text = trim(($r['question'] ?? '') . "\n" . ($r['answer'] ?? ''));
            if ($text === '') { continue; }

            try {
                $vec = $client->embed($text);
                $Faqs->updateAll(
                    ['embedding_json' => json_encode($vec, JSON_UNESCAPED_UNICODE)],
                    ['id' => $r['id']]
                );
                $done++;
            } catch (\Throwable $e) {
                $io->warning("id {$r['id']}: " . $e->getMessage());
            }
        }

        $io->out("Embedded $done FAQ rows.");
        return Command::CODE_SUCCESS;
    }
}
