<?php

namespace Modules\AiCore\Providers;

use Illuminate\Support\ServiceProvider;
use Modules\AiCore\Entities\Services\AiToolRegistry;

class AiCoreServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->registerConfig();
        $this->registerViews();
        $this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations');
        $this->registerTranslations();
    }

    public function register()
    {
        $this->app->register(RouteServiceProvider::class);

        // Single shared tool registry: other modules push their AiTools onto it
        // (e.g. WhatsApp registers the appointment-booking tool) and consumers
        // pull whitelisted tools by name when invoking the ToolRunner.
        $this->app->singleton(AiToolRegistry::class, function () {
            return new AiToolRegistry();
        });
    }

    protected function registerConfig()
    {
        $this->publishes([
            __DIR__ . '/../Config/config.php' => config_path('aicore.php'),
        ], 'config');
        $this->mergeConfigFrom(__DIR__ . '/../Config/config.php', 'aicore');
    }

    public function registerViews()
    {
        $viewPath   = resource_path('views/modules/AiCore');
        $sourcePath = __DIR__ . '/../Resources/views';

        $this->publishes([$sourcePath => $viewPath], 'views');

        $this->loadViewsFrom(array_merge(array_map(function ($path) {
            return $path . '/modules/aiCore';
        }, \Config::get('view.paths')), [$sourcePath]), 'aiCore');
    }

    public function registerTranslations()
    {
        $langPath = resource_path('lang/modules/AiCore');

        if (is_dir($langPath)) {
            $this->loadTranslationsFrom($langPath, 'aiCore');
        } else {
            $this->loadTranslationsFrom(__DIR__ . '/../Resources/lang', 'aiCore');
        }
    }

    public function provides()
    {
        return [];
    }
}
