<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Support\PluginIntegration;

use App\Support\PageContext\FilamentPageContextCapture;
use App\Tools\Context\ErpPageContext;
use App\Tools\Context\PageKind;
use Filament\Actions\Action;
use Livewire\Livewire;
use Throwable;

/**
 * 宿主挂载 DBErp AI 当前页「问 AI」与全局快捷入口。插件未安装时返回空数组或空字符串。
 */
final class DberpAiPageContextFilamentBridge
{
    private const INTEGRATION_CLASS = 'Loongdom\DberpAi\Filament\DberpAiHostFilamentActions';

    /**
     * @return list<Action>
     */
    public static function recordHeaderActionsFor(mixed $record, PageKind $pageKind): array
    {
        $context = app(FilamentPageContextCapture::class)->fromPersistedRecord($record, $pageKind);

        return self::recordHeaderActions($context);
    }

    /**
     * @return list<Action>
     */
    public static function recordHeaderActions(?ErpPageContext $context): array
    {
        if (! $context instanceof ErpPageContext) {
            return [];
        }

        return OptionalPluginClassDelegate::call(
            self::INTEGRATION_CLASS,
            static fn (string $integrationClass): mixed => $integrationClass::recordHeaderActions($context),
            [],
        );
    }

    public static function globalLauncherHtml(): string
    {
        $html = OptionalPluginClassDelegate::call(
            self::INTEGRATION_CLASS,
            static fn (string $integrationClass): mixed => $integrationClass::globalLauncherHtml(),
            '',
        );

        return is_string($html) ? $html : '';
    }

    public static function pageContextMarkerHtml(): string
    {
        $html = OptionalPluginClassDelegate::call(
            self::INTEGRATION_CLASS,
            static function (string $integrationClass): mixed {
                try {
                    $page = Livewire::current();
                } catch (Throwable) {
                    $page = null;
                }

                $context = app(FilamentPageContextCapture::class)->fromCurrentLivewirePage($page);

                return $integrationClass::pageContextMarkerHtml($context);
            },
            '',
        );

        return is_string($html) ? $html : '';
    }
}
