<?php

namespace Database\Seeders;

use App\Models\Guide;
use App\Models\GuidePage;
use App\Models\GuidePageEdge;
use App\Models\Station;
use App\Models\User;
use Illuminate\Database\Seeder;

class GuideSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->command->info('开始创建操作指引数据...');

        $admin = User::where('email', 'admin@example.com')->first();
        $stations = Station::all();

        // 1. 如何用光（带分支）
        $guide1 = $this->createHowToUseBeamGuide($admin);

        // 2. 真空阀门故障处理
        $guide2 = $this->createVacuumValveIssueGuide($admin);

        // 3. 漏水报警处理
        $guide3 = $this->createWaterLeakAlarmGuide($admin);

        // 将指引关联到所有线站（非全局，关联所有线站 = 各线站均可见）
        $this->command->info('关联指引到所有线站...');
        $stationIds = $stations->pluck('id')->toArray();
        $guide1->stations()->attach($stationIds);
        $guide2->stations()->attach($stationIds);
        $guide3->stations()->attach($stationIds);

        $this->command->info('操作指引数据创建完成！');
        $this->command->info('  - 指引数量: ' . Guide::count());
        $this->command->info('  - 指引页面数量: ' . GuidePage::count());
        $this->command->info('  - 指引边数量: ' . GuidePageEdge::count());
        $this->command->info('  - 关联线站数量: ' . $stations->count());
    }

    private function placeholder(string $title): string
    {
        return '<p>本步骤说明待补充。管理员可在 Filament 后台使用富文本编辑器完善「' . e($title) . '」的操作指引。</p>';
    }

    private function createHowToUseBeamGuide(User $admin): Guide
    {
        $this->command->info('创建指引: 如何用光...');

        $guide = Guide::create([
            'name' => '如何用光',
            'description' => '光束线用光操作完整流程指引，包含前门12和后门两条路径',
            'category' => 'operation',
            'tags' => ['用光', '光闸', 'PS1', '光学棚屋'],
            'status' => 'published',
            'created_by' => $admin->id,
            'published_at' => now(),
        ]);

        $step1 = GuidePage::create([
            'guide_id' => $guide->id,
            'title' => '打开光子光闸 PS1',
            'content' => $this->placeholder('打开光子光闸 PS1'),
        ]);

        $step2 = GuidePage::create([
            'guide_id' => $guide->id,
            'title' => '搜索光学棚屋',
            'content' => $this->placeholder('搜索光学棚屋'),
            'options' => ['前门12', '后门'],
        ]);

        $step3a = GuidePage::create([
            'guide_id' => $guide->id,
            'title' => '前门12路径 - 检查设备状态',
            'content' => $this->placeholder('前门12路径 - 检查设备状态'),
        ]);

        $step3b = GuidePage::create([
            'guide_id' => $guide->id,
            'title' => '后门路径 - 安全确认',
            'content' => $this->placeholder('后门路径 - 安全确认'),
        ]);

        $step4a = GuidePage::create([
            'guide_id' => $guide->id,
            'title' => '前门12路径 - 打开实验站光闸',
            'content' => $this->placeholder('前门12路径 - 打开实验站光闸'),
        ]);

        $step4b = GuidePage::create([
            'guide_id' => $guide->id,
            'title' => '后门路径 - 设备检查',
            'content' => $this->placeholder('后门路径 - 设备检查'),
        ]);

        $step5 = GuidePage::create([
            'guide_id' => $guide->id,
            'title' => '完成',
            'content' => $this->placeholder('完成'),
        ]);

        // step1 → step2 (sequential)
        GuidePageEdge::create([
            'guide_id' => $guide->id,
            'from_page_id' => $step1->id,
            'to_page_id' => $step2->id,
            'label' => null,
            'sort' => 0,
        ]);

        // step2 → step3a (branching option: 前门12)
        GuidePageEdge::create([
            'guide_id' => $guide->id,
            'from_page_id' => $step2->id,
            'to_page_id' => $step3a->id,
            'label' => '前门12',
            'sort' => 0,
        ]);

        // step2 → step3b (branching option: 后门)
        GuidePageEdge::create([
            'guide_id' => $guide->id,
            'from_page_id' => $step2->id,
            'to_page_id' => $step3b->id,
            'label' => '后门',
            'sort' => 1,
        ]);

        // step3a → step4a (sequential)
        GuidePageEdge::create([
            'guide_id' => $guide->id,
            'from_page_id' => $step3a->id,
            'to_page_id' => $step4a->id,
            'label' => null,
            'sort' => 0,
        ]);

        // step3b → step4b (sequential)
        GuidePageEdge::create([
            'guide_id' => $guide->id,
            'from_page_id' => $step3b->id,
            'to_page_id' => $step4b->id,
            'label' => null,
            'sort' => 0,
        ]);

        // step4a → step5 (convergence)
        GuidePageEdge::create([
            'guide_id' => $guide->id,
            'from_page_id' => $step4a->id,
            'to_page_id' => $step5->id,
            'label' => null,
            'sort' => 0,
        ]);

        // step4b → step5 (convergence)
        GuidePageEdge::create([
            'guide_id' => $guide->id,
            'from_page_id' => $step4b->id,
            'to_page_id' => $step5->id,
            'label' => null,
            'sort' => 0,
        ]);

        return $guide;
    }

    private function createVacuumValveIssueGuide(User $admin): Guide
    {
        $this->command->info('创建指引: 真空阀门故障处理...');

        $guide = Guide::create([
            'name' => '真空阀门故障处理',
            'description' => '真空阀门异常时的排查和处理流程',
            'category' => 'fault_handling',
            'tags' => ['真空', '阀门', '故障', '联锁', '气动'],
            'status' => 'published',
            'created_by' => $admin->id,
            'published_at' => now(),
        ]);

        $steps = [
            '检查真空度',
            '检查联锁状态',
            '尝试手动复位',
            '检查气动系统',
            '联系维护人员',
        ];

        $pages = [];
        foreach ($steps as $title) {
            $pages[] = GuidePage::create([
                'guide_id' => $guide->id,
                'title' => $title,
                'content' => $this->placeholder($title),
            ]);
        }

        // Sequential edges: A→B→C→D→E
        for ($i = 0; $i < count($pages) - 1; $i++) {
            GuidePageEdge::create([
                'guide_id' => $guide->id,
                'from_page_id' => $pages[$i]->id,
                'to_page_id' => $pages[$i + 1]->id,
                'label' => null,
                'sort' => 0,
            ]);
        }

        return $guide;
    }

    private function createWaterLeakAlarmGuide(User $admin): Guide
    {
        $this->command->info('创建指引: 漏水报警处理...');

        $guide = Guide::create([
            'name' => '漏水报警处理',
            'description' => '漏水报警时的应急处理和复位流程',
            'category' => 'fault_handling',
            'tags' => ['漏水', '报警', '应急', '复位'],
            'status' => 'published',
            'created_by' => $admin->id,
            'published_at' => now(),
        ]);

        $steps = [
            '确认报警位置',
            '搜索光学棚屋',
            '定位并处理漏水点',
            '复位报警',
            '完成',
        ];

        $pages = [];
        foreach ($steps as $title) {
            $pages[] = GuidePage::create([
                'guide_id' => $guide->id,
                'title' => $title,
                'content' => $this->placeholder($title),
            ]);
        }

        // Sequential edges: A→B→C→D→E
        for ($i = 0; $i < count($pages) - 1; $i++) {
            GuidePageEdge::create([
                'guide_id' => $guide->id,
                'from_page_id' => $pages[$i]->id,
                'to_page_id' => $pages[$i + 1]->id,
                'label' => null,
                'sort' => 0,
            ]);
        }

        return $guide;
    }
}
