<?php

declare(strict_types=1);

namespace Database\Seeders;

use App\Domain\Plugin\PluginManager;
use App\Settings\AiSettings;
use Illuminate\Database\Seeder;

/**
 * Sync AI settings from .env into Spatie settings, and enable comment moderation.
 *
 * Credentials stay in .env (gitignored); this seeder only copies them into the DB
 * so Filament / LlmProvider pick them up after the initial settings migration.
 */
class AiSettingsSeeder extends Seeder
{
    public function run(): void
    {
        $settings = app(AiSettings::class);

        $settings->provider = (string) env('AI_PROVIDER', 'openai_compatible');
        $settings->api_base_url = env('AI_API_BASE_URL') ?: $settings->api_base_url;
        $settings->api_key = env('AI_API_KEY') ?: $settings->api_key;
        $settings->model = env('AI_MODEL') ?: $settings->model;
        $settings->comment_moderation_enabled = true;
        $settings->content_optimization_enabled = true;
        $settings->save();

        $plugins = app(PluginManager::class);
        $plugins->syncDiscoveredPlugins();

        try {
            $plugins->enable('larablog/ai-comment-moderation');
        } catch (\Throwable $e) {
            $this->command?->warn('Could not enable ai-comment-moderation: '.$e->getMessage());
        }

        $this->command?->info(sprintf(
            'AI settings saved: provider=%s model=%s base=%s key=%s',
            $settings->provider,
            $settings->model ?? '(none)',
            $settings->api_base_url ?? '(none)',
            filled($settings->api_key) ? '****'.substr((string) $settings->api_key, -4) : '(empty)',
        ));
    }
}
