<?php

namespace Modules\AICore\App\Providers;

use App\Traits\RegistersMenuItems;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class AICoreServiceProvider extends ServiceProvider
{
    use PathNamespace;
    use RegistersMenuItems;

    protected string $name = 'AICore';

    protected string $nameLower = 'aicore';

    /**
     * Boot the application events.
     */
    public function boot(): void
    {
        $this->registerCommands();
        $this->registerCommandSchedules();
        $this->registerTranslations();
        $this->registerConfig();
        $this->registerViews();
        $this->loadMigrationsFrom(module_path($this->name, 'Database/migrations'));
        $this->registerMenuItems();
        $this->registerSettings();
    }

    /**
     * Register the service provider.
     */
    public function register(): void
    {
        $this->app->register(EventServiceProvider::class);
        $this->app->register(RouteServiceProvider::class);
    }

    /**
     * Register commands in the format of Command::class
     */
    protected function registerCommands(): void
    {
        // $this->commands([]);
    }

    /**
     * Register command Schedules.
     */
    protected function registerCommandSchedules(): void
    {
        // $this->app->booted(function () {
        //     $schedule = $this->app->make(Schedule::class);
        //     $schedule->command('inspire')->hourly();
        // });
    }

    /**
     * Register translations.
     */
    public function registerTranslations(): void
    {
        $langPath = resource_path('lang/modules/'.$this->nameLower);

        if (is_dir($langPath)) {
            $this->loadTranslationsFrom($langPath, $this->nameLower);
            $this->loadJsonTranslationsFrom($langPath);
        } else {
            $this->loadTranslationsFrom(module_path($this->name, 'lang'), $this->nameLower);
            $this->loadJsonTranslationsFrom(module_path($this->name, 'lang'));
        }
    }

    /**
     * Register config.
     */
    protected function registerConfig(): void
    {
        $relativeConfigPath = config('modules.paths.generator.config.path');
        $configPath = module_path($this->name, $relativeConfigPath);

        if (is_dir($configPath)) {
            $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($configPath));

            foreach ($iterator as $file) {
                if ($file->isFile() && $file->getExtension() === 'php') {
                    $relativePath = str_replace($configPath.DIRECTORY_SEPARATOR, '', $file->getPathname());
                    $configKey = $this->nameLower.'.'.str_replace([DIRECTORY_SEPARATOR, '.php'], ['.', ''], $relativePath);
                    $key = ($relativePath === 'config.php') ? $this->nameLower : $configKey;

                    $this->publishes([$file->getPathname() => config_path($relativePath)], 'config');
                    $this->mergeConfigFrom($file->getPathname(), $key);
                }
            }
        }
    }

    /**
     * Register views.
     */
    public function registerViews(): void
    {
        $viewPath = resource_path('views/modules/'.$this->nameLower);
        $sourcePath = module_path($this->name, 'resources/views');

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

        $this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), $this->nameLower);

        $componentNamespace = $this->module_namespace($this->name, $this->app_path(config('modules.paths.generator.component-class.path')));
        Blade::componentNamespace($componentNamespace, $this->nameLower);
    }

    /**
     * Get the services provided by the provider.
     */
    public function provides(): array
    {
        return [];
    }

    private function getPublishableViewPaths(): array
    {
        $paths = [];
        foreach (config('view.paths') as $path) {
            if (is_dir($path.'/modules/'.$this->nameLower)) {
                $paths[] = $path.'/modules/'.$this->nameLower;
            }
        }

        return $paths;
    }

    /**
     * Get the menu items for this module.
     *
     * @return array<array<string, mixed>>
     */
    protected function getMenuItems(): array
    {
        return [
            [
                'name' => 'AI Hub',
                'icon' => 'menu-icon bx bx-brain',
                'menuKey' => 'ai-hub', // Parent key for all AI modules
                'roles' => ['super_admin', 'admin'],
                'addon' => 'AICore',
                'slug' => [
                    'aicore.dashboard',
                    'aicore.providers.index',
                    'aicore.providers.create',
                    'aicore.providers.edit',
                    'aicore.providers.show',
                    'aicore.models.index',
                    'aicore.models.create',
                    'aicore.models.edit',
                    'aicore.models.show',
                    'aicore.usage.index',
                    'aicore.usage.show',
                    'aicore.logs.index',
                    'aicore.logs.show',
                    'aicore.module-configuration.index',
                    'aicore.settings.index',
                    'localaiprovider.settings.index',
                ],
                'submenu' => [
                    // AI Settings submenu - always present as last item
                    [
                        'name' => 'AI Settings',
                        'icon' => 'menu-icon bx bx-cog',
                        'slug' => [
                            'aicore.dashboard',
                            'aicore.providers.index',
                            'aicore.models.index',
                            'aicore.usage.index',
                            'aicore.logs.index',
                            'aicore.module-configuration.index',
                            'aicore.settings.index',
                            'localaiprovider.settings.index',
                        ],
                        'submenu' => [
                            [
                                'url' => '/aicore/dashboard',
                                'name' => 'Dashboard',
                                'slug' => 'aicore.dashboard',
                            ],
                            [
                                'url' => '/aicore/providers',
                                'name' => 'Providers',
                                'slug' => 'aicore.providers.index',
                            ],
                            [
                                'url' => '/aicore/models',
                                'name' => 'Models',
                                'slug' => 'aicore.models.index',
                            ],
                            [
                                'url' => '/aicore/usage',
                                'name' => 'Usage Analytics',
                                'slug' => 'aicore.usage.index',
                            ],
                            [
                                'url' => '/aicore/logs',
                                'name' => 'Request Logs',
                                'slug' => 'aicore.logs.index',
                            ],
                            [
                                'url' => '/aicore/module-configuration',
                                'name' => 'Module Config',
                                'slug' => 'aicore.module-configuration.index',
                            ],
                            [
                                'url' => '/localaiprovider/settings',
                                'name' => 'Local AI Settings',
                                'slug' => 'localaiprovider.settings.index',
                                'addon' => 'LocalAIProvider',
                            ],
                            [
                                'url' => '/aicore/settings',
                                'name' => 'Settings',
                                'slug' => 'aicore.settings.index',
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }

    /**
     * Get the menu priority for this module.
     * Lower values appear higher in the menu.
     */
    protected function getMenuPriority(): int
    {
        return 85; // AI Hub parent - first among AI modules
    }

    /**
     * Register module settings.
     */
    private function registerSettings(): void
    {
        if (class_exists(\App\Services\Settings\SettingsRegistry::class)) {
            $settingsRegistry = $this->app->make(\App\Services\Settings\SettingsRegistry::class);
            $settingsRegistry->registerModule('AICore', [
                'handler' => \Modules\AICore\App\Settings\AICoreSettings::class,
                'permissions' => ['aicore.settings.manage'],
                'name' => __('AI Core Settings'),
                'icon' => 'bx bx-brain',
                'description' => __('Configure AI providers, models, and usage settings'),
            ]);
        }
    }
}
