<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\AcademicVersion;
use App\Models\Subject;
use App\Models\SubjectPaper;
use App\Models\GroupSubject;
use App\Models\SubjectBucket;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class HSCSubjectSeeder extends Seeder
{
    public function run()
    {
        Schema::disableForeignKeyConstraints();
        SubjectPaper::truncate();
        GroupSubject::truncate();
        SubjectBucket::truncate();
        DB::table('subject_bucket_items')->truncate();
        // We use updateOrCreate for subjects to avoid ID conflicts if seeded over, 
        // but for a clean state in dev, truncating is cleaner if allowed.
        // Assuming development env, let's truncate Subject to ensure clean slate.
        Subject::truncate();
        Schema::enableForeignKeyConstraints();

        $this->command->info('Migration cleared. Seeding HSC 2025 Rules...');

        // 1. Create Academic Version
        $version = AcademicVersion::firstOrCreate(
            ['name' => 'HSC 2025'],
            ['effective_from' => '2025-01-01', 'is_current' => true]
        );

        // 2. Define All Subjects
        $subjects = [
            // Core
            ['name' => 'Bangla', 'short' => 'BAN', 'codes' => ['101', '102'], 'practical' => false],
            ['name' => 'English', 'short' => 'ENG', 'codes' => ['107', '108'], 'practical' => false],
            ['name' => 'Information & Communication Technology', 'short' => 'ICT', 'codes' => ['275'], 'practical' => true],
            
            // Science
            ['name' => 'Physics', 'short' => 'PHY', 'codes' => ['174', '175'], 'practical' => true],
            ['name' => 'Chemistry', 'short' => 'CHEM', 'codes' => ['176', '177'], 'practical' => true],
            ['name' => 'Higher Mathematics', 'short' => 'MATH', 'codes' => ['265', '266'], 'practical' => true],
            ['name' => 'Biology', 'short' => 'BIO', 'codes' => ['178', '179'], 'practical' => true],
            ['name' => 'Statistics', 'short' => 'STAT', 'codes' => ['129', '130'], 'practical' => true],
            ['name' => 'Psychology', 'short' => 'PSY', 'codes' => ['123', '124'], 'practical' => true],

            // Commerce
            ['name' => 'Accounting', 'short' => 'ACC', 'codes' => ['253', '254'], 'practical' => false],
            ['name' => 'Business Organization & Management', 'short' => 'BOM', 'codes' => ['277', '278'], 'practical' => false],
            ['name' => 'Finance, Banking & Insurance', 'short' => 'FIN', 'codes' => ['292', '293'], 'practical' => false],
            ['name' => 'Production Management & Marketing', 'short' => 'PMM', 'codes' => ['286', '287'], 'practical' => false],
            
            // Humanities
            ['name' => 'History', 'short' => 'HIS', 'codes' => ['304', '305'], 'practical' => false],
            ['name' => 'Islamic History & Culture', 'short' => 'IHC', 'codes' => ['267', '268'], 'practical' => false],
            ['name' => 'Civics & Good Governance', 'short' => 'CIV', 'codes' => ['269', '270'], 'practical' => false],
            ['name' => 'Economics', 'short' => 'ECO', 'codes' => ['109', '110'], 'practical' => false],
            ['name' => 'Social Work', 'short' => 'SW', 'codes' => ['271', '272'], 'practical' => false],
            ['name' => 'Sociology', 'short' => 'SOC', 'codes' => ['117', '118'], 'practical' => false],
            ['name' => 'Geography', 'short' => 'GEO', 'codes' => ['125', '126'], 'practical' => true],
            ['name' => 'Logic', 'short' => 'LOG', 'codes' => ['121', '122'], 'practical' => false],
            ['name' => 'Agricultural Studies', 'short' => 'AGRI', 'codes' => ['239', '240'], 'practical' => true],
        ];

        
        $subjectMap = []; // To store created subject IDs

        foreach ($subjects as $data) {
            $isDouble = count($data['codes']) > 1;
            $mainCode = $data['codes'][0];

            $sub = Subject::create([
                    'name' => $data['name'],
                    'short_name' => $data['short'],
                    'code' => $mainCode,
                    'has_multiple_papers' => $isDouble,
                    'is_4th_subject_eligible' => true
                ]);

                $subjectMap[$data['name']] = $sub->id;

            // Create Papers
            if ($isDouble) {
                // Paper 1
                SubjectPaper::create([
                    'subject_id' => $sub->id,
                    'paper_type' => 'first',
                    'paper_code' => $data['codes'][0],
                    'name_suffix' => '1st Paper',
                    'has_cq' => true,
                    'has_mcq' => true,
                    'has_practical' => $data['practical']
                ]);
                // Paper 2
                SubjectPaper::create([
                    'subject_id' => $sub->id,
                    'paper_type' => 'second',
                    'paper_code' => $data['codes'][1],
                    'name_suffix' => '2nd Paper',
                    'has_cq' => true,
                    'has_mcq' => true,
                    'has_practical' => $data['practical']
                ]);
            } else {
                // Single Paper
                SubjectPaper::create([
                    'subject_id' => $sub->id,
                    'paper_type' => 'single',
                    'paper_code' => $data['codes'][0],
                    'name_suffix' => null,
                    'has_cq' => true,
                    'has_mcq' => true,
                    'has_practical' => $data['practical']
                ]);
            }
        }

        $this->command->info('Subjects & Papers seeded.');

        // 3. Configure Rules (The Matrix)
        
        $groups = ['science', 'commerce', 'arts'];

        // --- Core Subjects (All Groups) ---
        $coreNames = ['Bangla', 'English', 'Information & Communication Technology'];
        foreach ($groups as $group) {
            foreach ($coreNames as $name) {
                if (isset($subjectMap[$name])) {
                    GroupSubject::create([
                        'academic_version_id' => $version->id,
                        'subject_id' => $subjectMap[$name],
                        'group_code' => $group,
                        'category' => 'core',
                        'is_mandatory' => true
                    ]);
                }
            }
        }

        // --- Science Rules ---
        // Mandatory: Physics, Chemistry
        $sciMandatory = ['Physics', 'Chemistry'];
        foreach ($sciMandatory as $name) {
            GroupSubject::create([
                'academic_version_id' => $version->id,
                'subject_id' => $subjectMap[$name],
                'group_code' => 'science',
                'category' => 'group_main',
                'is_mandatory' => true
            ]);
        }

        // Bucket: 3rd Main (Bio or Math)
        $bucket3rd = SubjectBucket::create([
            'academic_version_id' => $version->id,
            'group_code' => 'science',
            'name' => 'Compulsory Elective (3rd Main)',
            'min_select' => 1,
            'max_select' => 1,
            'ui_type' => 'radio'
        ]);
        $bucket3rd->subjects()->attach([$subjectMap['Biology'], $subjectMap['Higher Mathematics']]);

        // Bucket: 4th Optional (Bio/Math/Psych/Stat/Geog...)
        $bucket4th = SubjectBucket::create([
            'academic_version_id' => $version->id,
            'group_code' => 'science',
            'name' => 'Optional Subject (4th)',
            'min_select' => 0,
            'max_select' => 1,
            'ui_type' => 'radio' // Even if optional, user picks 1 or 0
        ]);
        $bucket4th->subjects()->attach([
            $subjectMap['Biology'], 
            $subjectMap['Higher Mathematics'],
            $subjectMap['Statistics'],
            $subjectMap['Psychology'],
            $subjectMap['Geography']
        ]);

        // --- Commerce Rules ---
        // Mandatory: Accounting, BOM, Fin
        $comMandatory = ['Accounting', 'Business Organization & Management', 'Finance, Banking & Insurance'];
        foreach ($comMandatory as $name) {
             GroupSubject::create([
                'academic_version_id' => $version->id,
                'subject_id' => $subjectMap[$name],
                'group_code' => 'commerce',
                'category' => 'group_main',
                'is_mandatory' => true
            ]);
        }
        
        // Bucket: 4th Optional
        $bucket4thCom = SubjectBucket::create([
            'academic_version_id' => $version->id,
            'group_code' => 'commerce',
            'name' => 'Optional Subject (4th)',
            'min_select' => 0,
            'max_select' => 1,
            'ui_type' => 'radio'
        ]);
        $bucket4thCom->subjects()->attach([
            $subjectMap['Production Management & Marketing'],
            $subjectMap['Statistics'],
            $subjectMap['Economics'],
            $subjectMap['Geography'],
            $subjectMap['Agricultural Studies']
        ]);


        // --- Humanities Rules ---
        // 3 Main Subjects from Pool
        $bucketArtsMain = SubjectBucket::create([
            'academic_version_id' => $version->id,
            'group_code' => 'arts',
            'name' => 'Group Main Subjects',
            'min_select' => 3,
            'max_select' => 3,
            'ui_type' => 'checkbox'
        ]);
        
        $artsPool = [
            'History', 'Islamic History & Culture', 'Civics & Good Governance', 
            'Economics', 'Social Work', 'Sociology', 'Geography', 'Logic', 'Psychology'
        ];
        
        $artsIds = [];
        foreach($artsPool as $n) if(isset($subjectMap[$n])) $artsIds[] = $subjectMap[$n];
        $bucketArtsMain->subjects()->attach($artsIds);

        // 4th Optional Pool
        $bucketArts4th = SubjectBucket::create([
            'academic_version_id' => $version->id,
            'group_code' => 'arts',
            'name' => 'Optional Subject (4th)',
            'min_select' => 0,
            'max_select' => 1,
            'ui_type' => 'radio'
        ]);
        // Same pool mostly + Agri + Stats
        $arts4thPool = array_merge($artsPool, ['Statistics', 'Agricultural Studies']);
        $arts4thIds = [];
        foreach($arts4thPool as $n) if(isset($subjectMap[$n])) $arts4thIds[] = $subjectMap[$n];
        $bucketArts4th->subjects()->attach($arts4thIds);

        $this->command->info('HSC 2025 Rules Seeded Successfully.');
    }
}
