<?php

namespace Database\Seeders;

use App\Models\KnowledgeBase;
use App\Models\Station;
use App\Models\Terminal;
use Illuminate\Database\Seeder;

class TerminalSeeder extends Seeder
{
    public function run(): void
    {
        $this->command->info('开始创建线站、知识库和终端...');

        $beamlines = [
            'BL02U1' => '192.168.1.21',
            'BL07U' => '192.168.1.27',
            'BL08U' => '192.168.1.28',
            'BL13HB' => '192.168.1.33',
            'BL13U' => '192.168.1.34',
            'BL14B' => '192.168.1.35',
            'BL14W' => '192.168.1.36',
            'BL15U' => '192.168.1.37',
            'BL16B' => '192.168.1.38',
            'BL16U1' => '192.168.1.39',
        ];

        // 创建通用知识库（全局，不关联线站）
        $this->command->info('创建通用知识库...');
        KnowledgeBase::create(['name' => '通用知识库', 'description' => '全站通用的规章制度和管理文档', 'status' => 'active']);

        foreach ($beamlines as $beamline => $ipAddress) {
            // 创建线站
            $station = Station::firstOrCreate(['name' => $beamline]);

            // 创建线站专属知识库并关联
            $kb = KnowledgeBase::create([
                'name' => "{$beamline} 知识库",
                'description' => "{$beamline} 光束线专用文档",
                'status' => 'active',
            ]);
            $station->knowledgeBases()->attach($kb);

            // 创建终端
            $terminal = Terminal::create([
                'name' => "{$beamline} 智慧屏",
                'code' => "SCREEN-{$beamline}",
                'ip_address' => $ipAddress,
                'station_id' => $station->id,
                'prompt_template' => "你是{$beamline}光束线的AI助手（终端: {terminal_name} / {terminal_code}）。当前时间是{time}。请根据用户{user}的问题，提供准确的光束线操作指导、实验支持和技术咨询。",
                'diagram_urls' => [
                    ['title' => 'BL16U1', 'url' => 'https://ssrf.9z.work/scada/BL16U1.svg'],
                    ['title' => 'BL16U1前端布局图', 'url' => 'https://ssrf.9z.work/scada/BL16U1-1.svg']
                ],
                'is_online' => in_array($beamline, ['BL02U1', 'BL07U', 'BL08U', 'BL13U', 'BL15U']),
                'last_online_at' => in_array($beamline, ['BL02U1', 'BL07U', 'BL08U', 'BL13U', 'BL15U'])
                    ? now()
                    : now()->subHours(rand(1, 24)),
            ]);
        }

        $this->command->info('线站/知识库/终端创建完成！');
        $this->command->info('  - 线站: ' . Station::count());
        $this->command->info('  - 知识库: ' . KnowledgeBase::count());
        $this->command->info('  - 终端: ' . Terminal::count());
    }
}
