<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Blade;
use App\Models\MarkdownImport;
use App\Models\PreQuestionCandidate;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        // 注册 MathRecSys 服务
        $this->app->singleton(\App\Services\MathRecSysService::class, function () {
            return new \App\Services\MathRecSysService();
        });

        // 注册知识图谱服务
        $this->app->singleton(\App\Services\KnowledgeGraphService::class, function ($app) {
            return new \App\Services\KnowledgeGraphService(
                $app->make(\App\Services\MathRecSysService::class)
            );
        });

        // 注册PDF合并工具
        $this->app->singleton(\App\Services\PdfMerger::class, function () {
            return new \App\Services\PdfMerger();
        });
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // 通过代理访问时强制 https（检测 X-Forwarded-Proto 头）
        // 外部用户通过 https 代理访问 → 生成 https 链接
        // 内部容器通信 → 保持 http 链接
        if (request()->header('X-Forwarded-Proto') === 'https') {
            URL::forceScheme('https');
        }

        // 注册年级格式化 Blade 组件
        Blade::directive('formatGrade', function ($expression) {
            return "<?php echo format_grade($expression); ?>";
        });

        MarkdownImport::updated(function (MarkdownImport $import): void {
            try {
                Redis::publish('markdown-imports', json_encode([
                    'type' => 'markdown-imports',
                    'id' => $import->id,
                    'status' => $import->status,
                    'progress_stage' => $import->progress_stage,
                    'progress_message' => $import->progress_message,
                    'parsed_count' => $import->parsed_count ?? null,
                    'accepted_count' => $import->accepted_count ?? null,
                    'import_id' => $import->id,
                ], JSON_UNESCAPED_UNICODE));
            } catch (\Throwable $e) {
                // SSE publish failed, ignore to avoid affecting business flow.
            }
        });

        PreQuestionCandidate::updated(function (PreQuestionCandidate $candidate): void {
            try {
                Redis::publish('pre-question-candidates', json_encode([
                    'type' => 'pre-question-candidates',
                    'id' => $candidate->id,
                    'import_id' => $candidate->import_id,
                    'status' => $candidate->status,
                    'is_question_candidate' => $candidate->is_question_candidate,
                ], JSON_UNESCAPED_UNICODE));
            } catch (\Throwable $e) {
                // SSE publish failed, ignore to avoid affecting business flow.
            }
        });
    }
}
