<?php

namespace Kylin\Scaffold\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class ScaffoldInstallCommand extends Command
{
    protected $signature = 'kylin:scaffold-install
        {--all : 安装所有 Kylin 包}
        {--force : 强制重新安装}
        {--skip-migration : 跳过数据库迁移}';

    protected $description = '安装 Kylin 脚手架（交互式选择安装模块）';

    /**
     * 可安装的 Kylin 模块
     */
    private array $modules = [
        'core'        => ['label' => '核心基础',     'required' => true,  'config_tag' => 'kylin-core-config'],
        'licensing'   => ['label' => '许可证管理',   'required' => true,  'config_tag' => 'kylin-licensing-config'],
        'rbac'        => ['label' => 'RBAC 权限',    'required' => true,  'command' => 'kylin:rbac-install'],
        'user'        => ['label' => '用户管理',     'required' => false, 'config_tag' => 'kylin-user-config'],
        'auth'        => ['label' => '认证授权',     'required' => false, 'config_tag' => 'kylin-auth-config'],
        'notification'=> ['label' => '通知系统',     'required' => false, 'config_tag' => 'kylin-notification-config'],
        'storage'     => ['label' => '多云存储',     'required' => false, 'config_tag' => 'kylin-storage-config'],
        'excel'       => ['label' => 'Excel 导入导出', 'required' => false, 'config_tag' => 'kylin-excel-config'],
        'settings'    => ['label' => '系统设置',     'required' => false, 'config_tag' => 'kylin-settings-config'],
        'audit-log'   => ['label' => '审计日志',     'required' => false, 'config_tag' => 'kylin-audit-log-config'],
        'dictionary'  => ['label' => '数据字典',     'required' => false, 'config_tag' => 'kylin-dictionary-config'],
        'adminlte'    => ['label' => 'AdminLTE 后台', 'required' => false, 'command' => 'kylin:adminlte:install'],
        'media'       => ['label' => '媒体管理',     'required' => false, 'config_tag' => 'kylin-media-config'],
        'activity'    => ['label' => '活动管理',     'required' => false, 'config_tag' => 'kylin-activity-config'],
        'world'       => ['label' => '地区数据',     'required' => false, 'command' => 'kylin:world:import'],
    ];

    public function handle(): int
    {
        $this->info('');
        $this->info('  ╔══════════════════════════════════════╗');
        $this->info('  ║     Kylin 企业级应用脚手架安装       ║');
        $this->info('  ╚══════════════════════════════════════╝');
        $this->info('');

        // 选择要安装的模块
        $selected = $this->selectModules();

        // 发布配置文件
        $this->publishConfigs($selected);

        // 执行模块安装命令
        $this->runModuleCommands($selected);

        // 数据库迁移
        if (!$this->option('skip-migration')) {
            $this->runMigrations();
        }

        // 生成应用密钥
        $this->generateKey();

        $this->info('');
        $this->info('  ✅ Kylin 脚手架安装完成！');
        $this->info('');
        $this->line('  下一步操作：');
        $this->line('    1. 配置 .env 中的数据库连接');
        $this->line('    2. 设置 KYLIN_LICENSE_KEY 许可证密钥');
        $this->line('    3. 运行 php artisan serve 启动开发服务器');
        $this->info('');

        return self::SUCCESS;
    }

    /**
     * 交互式选择要安装的模块
     */
    private function selectModules(): array
    {
        if ($this->option('all')) {
            return array_keys($this->modules);
        }

        $choices = [];
        $defaults = [];

        foreach ($this->modules as $key => $module) {
            $label = $module['label'];
            if ($module['required']) {
                $label .= ' (必选)';
                $defaults[] = $label;
            } else {
                $defaults[] = $label;
            }
            $choices[$label] = $key;
        }

        $selected = $this->choice(
            '选择要安装的模块（多选用逗号分隔）',
            array_keys($choices),
            implode(',', array_keys($choices)),
            null,
            true
        );

        // 必选模块始终包含
        $result = [];
        foreach ($this->modules as $key => $module) {
            if ($module['required']) {
                $result[] = $key;
            }
        }

        foreach ((array) $selected as $label) {
            $key = $choices[$label] ?? null;
            if ($key && !in_array($key, $result)) {
                $result[] = $key;
            }
        }

        return $result;
    }

    /**
     * 发布配置文件
     */
    private function publishConfigs(array $selected): void
    {
        $this->info('');
        $this->info('📦 发布配置文件...');

        foreach ($selected as $module) {
            $config = $this->modules[$module]['config_tag'] ?? null;
            if ($config) {
                $this->line("  → 发布 {$this->modules[$module]['label']} 配置");
                Artisan::call('vendor:publish', ['--tag' => $config, '--force' => $this->option('force')]);
            }
        }
    }

    /**
     * 执行模块安装命令
     */
    private function runModuleCommands(array $selected): void
    {
        $this->info('');
        $this->info('🔧 执行模块安装...');

        foreach ($selected as $module) {
            $command = $this->modules[$module]['command'] ?? null;
            if ($command) {
                $this->line("  → 安装 {$this->modules[$module]['label']}");
                Artisan::call($command, [], $this->getOutput());
            }
        }
    }

    /**
     * 运行数据库迁移
     */
    private function runMigrations(): void
    {
        $this->info('');
        $this->info('🗄️  运行数据库迁移...');

        Artisan::call('migrate', [
            '--force' => true,
            '--graceful' => true,
        ], $this->getOutput());
    }

    /**
     * 生成应用密钥
     */
    private function generateKey(): void
    {
        if (!config('app.key')) {
            $this->info('');
            $this->info('🔑 生成应用密钥...');
            Artisan::call('key:generate', ['--force' => true]);
        }
    }
}
