<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use App\Models\SongLibrary;
use App\Models\Song;
use App\Models\Artist;
use App\Enums\ArtistCategory;
use App\Enums\SongLanguageType;
use App\Enums\SongSituation;

class SqliteToMysqlSeeder extends Seeder
{
    public function run(): void
    {
        $SongCategoryMap = \App\Models\SongCategory::pluck('id', 'code')->toArray();

        $artistCache = [];
        $chunkSize = 100;
        $totalCount = 0;//51912
        SongLibrary::where('歌曲編號', '>', 0)->chunk($chunkSize, function ($songs) use ( $SongCategoryMap, &$artistCache, &$totalCount) {
            $songsToInsert = [];
            $pivotArtist = [];
            $pivotCategory = [];

            foreach ($songs as $data) {
                $totalCount++; // 這裡計數
                $songId = $data->{'歌曲編號'};
                $artistAId = null;
                $artistBId = null;

                // 處理 Artist A
                if (!empty($data->{'歌星 A'})) {
                    $key = $data->{'歌星 A'} . '|' . ($data->{'歌星A分類'} ?? '未定義');
                    if (!isset($artistCache[$key])) {
                        
                        
                        $artist = Artist::firstOrCreate([
                            'name' => $data->{'歌星 A'},
                            'category' => ArtistCategory::tryFrom(trim($data->{'歌星A分類'} ?? '未定義')) ?? ArtistCategory::Unset,
                            //'simplified' => $data->{'歌星A簡體'} ?? '',
                            //'phonetic_abbr' => $data->{'歌星A注音'} ?? '',
                            //'pinyin_abbr' => $data->{'歌星A拼音'} ?? '',
                            //'strokes_abbr' => 
                        ]);
                        $artistCache[$key] = $artist->id;
                    }
                    $artistAId = $artistCache[$key];
                }

                // 處理 Artist B
                if (!empty($data->{'歌星 B'})) {
                    $key = $data->{'歌星 B'} . '|' . ($data->{'歌星B分類'} ?? '未定義');
                    if (!isset($artistCache[$key])) {
                        $artist = Artist::firstOrCreate([
                            'name' => $data->{'歌星 B'},
                            'category' => ArtistCategory::tryFrom(trim($data->{'歌星B分類'} ?? '未定義')) ?? ArtistCategory::Unset,
                            //'simplified' => $data->{'歌星B簡體'} ?? '',
                            //'phonetic_abbr' => $data->{'歌星B注音'} ?? '',
                            //'pinyin_abbr' => $data->{'歌星B拼音'} ?? '',
                            //'strokes_abbr'
                        ]);
                        $artistCache[$key] = $artist->id;
                    }
                    $artistBId = $artistCache[$key];
                }
                // 處理 Song 資料
                $songsToInsert[] = [
                    'id' => $songId,
                    'name' => $data->{'歌曲名稱'},
                    'adddate' => $data->{'新增日期'},
                    'filename' => $data->{'歌曲檔名'},
                    'language_type' => SongLanguageType::tryFrom(trim($data->{'語別'} ?? '未定義')) ?? SongLanguageType::Unset,
                    'db_change' => $data->{'DB加減'} ?? 0,
                    'vocal' => $data->{'人聲'},
                    'situation' => SongSituation::tryFrom(trim($data->{'情境'} ?? '未定義')) ?? SongSituation::Unset,
                    'copyright01' => $data->{'版權01'},
                    'copyright02' => $data->{'版權02'},
                    'note01' => $data->{'版權03'},
                    'note02' => $data->{'版權04'},
                    'note03' => $data->{'版權05'},
                    'note04' => $data->{'版權06'},
                    'enable' => $data->{'狀態'},
                    'simplified' => $data->{'歌名簡體'} ?? '',
                    'phonetic_abbr' => $data->{'歌曲注音'} ?? '',
                    'pinyin_abbr' => $data->{'歌曲拼音'} ?? '',
                    'strokes_abbr' => $data->{'Unnamed: 21'} ?? 0,
                ];

                if ($artistAId) $pivotArtist[] = ['song_id' => $songId, 'artist_id' => $artistAId];
                if ($artistBId) $pivotArtist[] = ['song_id' => $songId, 'artist_id' => $artistBId];

                // 處理分類
                
                if (!empty($data->{'分類'})) {
                    $categoryCodes = explode(',', $data->{'分類'});
                    $addedCategoryIds = [];
                    foreach ($categoryCodes as $code) {
                        $code = trim($code);
                        if (isset($SongCategoryMap[$code])) {
                            $categoryId = $SongCategoryMap[$code];
                            if (!in_array($categoryId, $addedCategoryIds)) {
                                $pivotCategory[] = [
                                    'song_id' => $songId,
                                    'song_category_id' => $SongCategoryMap[$code]
                                ];
                                $addedCategoryIds[] = $categoryId;
                            }
                        }
                    }
                }
            }

            Song::insert($songsToInsert);
            DB::table('artist_song')->insert($pivotArtist);
            DB::table('song_song_category')->insert($pivotCategory);

            $this->command->info("目前累計處理 {$totalCount} 筆歌曲資料");
        });
        $this->command->info("全部完成，共處理 {$totalCount} 筆歌曲資料。");
    }
}
