<?php
/**
 * Scoring Formats Data Seeder
 * Populates the database with preset scoring formats from the JavaScript data
 */

require_once '../includes/db.php';

// The preset data from JavaScript
$presets = [
    [
        'id' => 'snowboard_slopestyle_sections_oi',
        'name' => 'Snowboard – Slopestyle (Sections+OI)',
        'sport' => 'snowboard',
        'judges' => ['min' => 5, 'max' => 7, 'scale' => [0, 100], 'drop' => 'none'],
        'mode' => 'sections_plus_oi',
        'sections' => ['count' => 6, 'weight' => 0.60],
        'oi' => ['weight' => 0.40],
        'rounds' => ['qualifying' => ['runs' => 2, 'agg' => 'best run'], 'final' => ['runs' => 3, 'agg' => 'best run']],
        'criteria' => [
            'sections' => ['Amplitude', 'Difficulty', 'Execution', 'Variety'],
            'oi' => ['Progression', 'Use of Course', 'Execution', 'Difficulty']
        ],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Run 1', 'Run 2', 'Best', 'Sections (Σ)', 'OI', 'Total']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['higher section total', 'higher OI', 'HJ vote']
    ],
    [
        'id' => 'snowboard_halfpipe_best_run',
        'name' => 'Snowboard – Halfpipe (Best Run)',
        'sport' => 'snowboard',
        'judges' => ['min' => 6, 'max' => 7, 'scale' => [0, 100], 'drop' => 'drop high/low'],
        'mode' => 'best_run',
        'rounds' => ['qualifying' => ['runs' => 2, 'agg' => 'best'], 'final' => ['runs' => 3, 'agg' => 'best']],
        'criteria' => ['oi' => ['Difficulty', 'Execution', 'Amplitude', 'Variety', 'Progression', 'Use of Pipe']],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Run 1', 'Run 2', 'Run 3', 'Best']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['2nd best run', '3rd best run', 'HJ vote']
    ],
    [
        'id' => 'snowboard_big_air_best_two',
        'name' => 'Snowboard – Big Air (Best 2)',
        'sport' => 'snowboard',
        'judges' => ['min' => 5, 'max' => 7, 'scale' => [0, 100], 'drop' => 'drop high/low'],
        'mode' => 'attempts_best_n',
        'attempts' => ['max' => 3, 'bestN' => 2, 'diversity' => 'different tricks/dirs'],
        'rounds' => ['qualifying' => ['runs' => 0, 'agg' => 'best 2 of 3'], 'final' => ['runs' => 0, 'agg' => 'best 2 of 3']],
        'criteria' => ['attempt' => ['Difficulty', 'Execution', 'Amplitude', 'Landing', 'Variety', 'Progression']],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Jump 1', 'Jump 2', 'Jump 3', 'Best Two', 'Total']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['highest jump', '2nd highest', 'HJ vote']
    ],
    [
        'id' => 'freeski_slopestyle_sections_oi',
        'name' => 'Freeski – Slopestyle (Sections+OI)',
        'sport' => 'freeski',
        'judges' => ['min' => 5, 'max' => 7, 'scale' => [0, 100], 'drop' => 'none'],
        'mode' => 'sections_plus_oi',
        'sections' => ['count' => 6, 'weight' => 0.60],
        'oi' => ['weight' => 0.40],
        'rounds' => ['qualifying' => ['runs' => 2, 'agg' => 'best'], 'final' => ['runs' => 3, 'agg' => 'best']],
        'criteria' => [
            'sections' => ['Amplitude', 'Difficulty', 'Execution', 'Variety'],
            'oi' => ['Progression', 'Use of Course', 'Execution', 'Difficulty']
        ],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Run 1', 'Run 2', 'Best', 'Sections (Σ)', 'OI', 'Total']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['higher section total', 'higher OI', 'HJ vote']
    ],
    [
        'id' => 'freeski_halfpipe_best_run',
        'name' => 'Freeski – Halfpipe (Best Run)',
        'sport' => 'freeski',
        'judges' => ['min' => 6, 'max' => 7, 'scale' => [0, 100], 'drop' => 'drop high/low'],
        'mode' => 'best_run',
        'rounds' => ['qualifying' => ['runs' => 2, 'agg' => 'best'], 'final' => ['runs' => 3, 'agg' => 'best']],
        'criteria' => ['oi' => ['Difficulty', 'Execution', 'Amplitude', 'Variety', 'Progression', 'Use of Pipe']],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Run 1', 'Run 2', 'Run 3', 'Best']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['2nd best run', '3rd best run', 'HJ vote']
    ],
    [
        'id' => 'freeski_big_air_best_two',
        'name' => 'Freeski – Big Air (Best 2)',
        'sport' => 'freeski',
        'judges' => ['min' => 5, 'max' => 7, 'scale' => [0, 100], 'drop' => 'drop high/low'],
        'mode' => 'attempts_best_n',
        'attempts' => ['max' => 3, 'bestN' => 2, 'diversity' => 'different tricks/dirs'],
        'rounds' => ['qualifying' => ['runs' => 0, 'agg' => 'best 2 of 3'], 'final' => ['runs' => 0, 'agg' => 'best 2 of 3']],
        'criteria' => ['attempt' => ['Difficulty', 'Execution', 'Amplitude', 'Landing', 'Variety', 'Progression']],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Jump 1', 'Jump 2', 'Jump 3', 'Best Two', 'Total']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['highest jump', '2nd highest', 'HJ vote']
    ],
    [
        'id' => 'skate_street_hybrid',
        'name' => 'Skateboarding – Street (Runs + Tricks)',
        'sport' => 'skateboard',
        'judges' => ['min' => 5, 'max' => 5, 'scale' => [0, 100], 'drop' => 'drop high/low'],
        'mode' => 'runs_plus_tricks',
        'runs' => ['perRound' => 2],
        'tricks' => ['attempts' => 5, 'bestN' => 2],
        'rounds' => ['qualifying' => ['runs' => 2, 'agg' => 'best run + best 2 tricks'], 'final' => ['runs' => 2, 'agg' => 'best run + best 2 tricks']],
        'criteria' => ['oi' => ['Difficulty', 'Execution', 'Variety', 'Amplitude', 'Flow', 'Use of Course']],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Run 1', 'Run 2', 'Best Run', 'Best Tricks (×2)', 'Total']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['best run', 'best trick', 'HJ vote']
    ],
    [
        'id' => 'skate_park_runs',
        'name' => 'Skateboarding – Park (Best Run)',
        'sport' => 'skateboard',
        'judges' => ['min' => 5, 'max' => 5, 'scale' => [0, 100], 'drop' => 'drop high/low'],
        'mode' => 'best_run',
        'rounds' => ['qualifying' => ['runs' => 3, 'agg' => 'best'], 'final' => ['runs' => 3, 'agg' => 'best']],
        'criteria' => ['oi' => ['Difficulty', 'Execution', 'Variety', 'Amplitude', 'Flow', 'Use of Park']],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Run 1', 'Run 2', 'Run 3', 'Best']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['2nd best run', '3rd best run', 'HJ vote']
    ],
    [
        'id' => 'bmx_freestyle_park',
        'name' => 'BMX Freestyle – Park',
        'sport' => 'bmx',
        'judges' => ['min' => 5, 'max' => 7, 'scale' => [0, 100], 'drop' => 'none'],
        'mode' => 'best_vs_avg',
        'rounds' => ['qualifying' => ['runs' => 2, 'agg' => 'average of 2'], 'final' => ['runs' => 2, 'agg' => 'best 1']],
        'criteria' => ['oi' => ['Difficulty', 'Progression', 'Variety', 'Creativity', 'Execution', 'Amplitude', 'Flow', 'Use of Course', 'Risk', 'Style']],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Run 1', 'Run 2', 'Average/Best', 'Total']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['highest single run', 'HJ vote']
    ],
    [
        'id' => 'inline_roller_freestyle',
        'name' => 'Inline – Roller Freestyle',
        'sport' => 'inline',
        'judges' => ['min' => 5, 'max' => 5, 'scale' => [0, 100], 'drop' => 'none'],
        'mode' => 'best_run',
        'rounds' => ['qualifying' => ['runs' => 2, 'agg' => 'best'], 'final' => ['runs' => 2, 'agg' => 'best']],
        'criteria' => ['oi' => ['Difficulty', 'Execution', 'Amplitude', 'Flow', 'Variety']],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Run 1', 'Run 2', 'Best']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['2nd best run', 'HJ vote']
    ],
    [
        'id' => 'wake_cable_features_air',
        'name' => 'Wakeboard – Cable (Features + Air)',
        'sport' => 'wakeboard',
        'judges' => ['min' => 5, 'max' => 5, 'scale' => [0, 100], 'drop' => 'none'],
        'mode' => 'best_run',
        'rounds' => ['qualifying' => ['runs' => 2, 'agg' => 'best'], 'final' => ['runs' => 2, 'agg' => 'best']],
        'criteria' => ['oi' => ['Composition/Variety', 'Intensity', 'Execution', 'Features vs Air Balance']],
        'results' => ['headers' => ['Rank', 'Bib', 'Name', 'Run 1', 'Run 2', 'Best']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['highest single run', 'HJ vote']
    ],
    [
        'id' => 'surf_two_best_waves',
        'name' => 'Surf – Best Two Waves',
        'sport' => 'surf',
        'judges' => ['min' => 5, 'max' => 5, 'scale' => [0, 10], 'precision' => 1, 'drop' => 'drop high/low per wave'],
        'mode' => 'attempts_best_n',
        'attempts' => ['max' => 12, 'bestN' => 2],
        'rounds' => ['heat' => ['runs' => 0, 'agg' => 'sum best 2 waves']],
        'criteria' => ['attempt' => ['Commitment', 'Innovation', 'Combo/Variety', 'Speed/Power/Flow']],
        'results' => ['headers' => ['Rank', 'Name', 'Wave 1', 'Wave 2', 'Wave 3', '…', 'Best Two', 'Total /20']],
        'flow' => ['Heats', 'Elimination', 'Final'],
        'tiebreak' => ['highest wave', '2nd highest', '3rd highest']
    ],
    [
        'id' => 'kitesurf_freestyle_tricks',
        'name' => 'Kitesurf – Freestyle (Best N + OI)',
        'sport' => 'kitesurf',
        'judges' => ['min' => 5, 'max' => 5, 'scale' => [0, 10], 'precision' => 1, 'drop' => 'drop high/low per trick'],
        'mode' => 'attempts_best_n_plus_oi',
        'attempts' => ['max' => 7, 'bestN' => 4],
        'oi' => ['weight' => 0.2],
        'rounds' => ['heat' => ['runs' => 0, 'agg' => 'sum best 4 + OI(20%)']],
        'criteria' => [
            'attempt' => ['Height/Extremity', 'Technicality', 'Variety', 'Innovation', 'Smoothness', 'Commitment'],
            'oi' => ['Overall Impression']
        ],
        'results' => ['headers' => ['Rank', 'Name', 'Trick Attempts', 'Best 4', 'OI', 'Total']],
        'flow' => ['Heats', 'Quarters', 'Semis', 'Final'],
        'tiebreak' => ['highest trick', '2nd highest', 'variety idx']
    ],
    [
        'id' => 'kitesurf_big_air',
        'name' => 'Kitesurf – Big Air (Best 3)',
        'sport' => 'kitesurf',
        'judges' => ['min' => 5, 'max' => 5, 'scale' => [0, 10], 'precision' => 1, 'drop' => 'drop high/low per trick'],
        'mode' => 'attempts_best_n',
        'attempts' => ['max' => 8, 'bestN' => 3],
        'rounds' => ['heat' => ['runs' => 0, 'agg' => 'sum best 3']],
        'criteria' => ['attempt' => ['Height', 'Extremity', 'Technicality', 'Control', 'Variety']],
        'results' => ['headers' => ['Rank', 'Name', 'Jump Attempts', 'Best 3', 'Total']],
        'flow' => ['Heats', 'Quarters', 'Semis', 'Final'],
        'tiebreak' => ['highest trick', '2nd highest']
    ],
    [
        'id' => 'parkour_freestyle_fig',
        'name' => 'Parkour – Freestyle (FIG)',
        'sport' => 'parkour',
        'judges' => ['min' => 6, 'max' => 6, 'scale' => 'E 0–15 + D open', 'drop' => 'components'],
        'mode' => 'components_ED',
        'rounds' => ['qualifying' => ['runs' => 1, 'agg' => 'E + top3 D - ded.'], 'final' => ['runs' => 1, 'agg' => 'E + top3 D - ded.']],
        'criteria' => ['E' => ['Safety/Landings', 'Flow', 'Quality'], 'D' => ['Difficulty via elements table']],
        'results' => ['headers' => ['Rank', 'Name', 'E total', 'D1', 'D2', 'D3', 'Ded.', 'Final']],
        'flow' => ['Qualification', 'Final'],
        'tiebreak' => ['higher E', 'higher D element', 'HJ vote']
    ],
    [
        'id' => 'breaking_wdsf_comparative',
        'name' => 'Breaking – WDSF Comparative',
        'sport' => 'breaking',
        'judges' => ['min' => 5, 'max' => 9, 'scale' => 'comparative', 'drop' => 'n/a'],
        'mode' => 'comparative',
        'criteria' => ['Technique', 'Vocabulary', 'Originality', 'Execution', 'Musicality'],
        'rounds' => ['battle' => ['runs' => 1, 'agg' => 'majority of criteria']],
        'results' => ['headers' => ['Battle', 'Bboy/Bgirl A', 'Bboy/Bgirl B', 'Technique', 'Vocabulary', 'Originality', 'Execution', 'Musicality', 'Winner']],
        'flow' => ['Top 16', 'Quarters', 'Semis', 'Final'],
        'tiebreak' => ['additional round', 'HJ decision']
    ]
];

// Diversity rules
$diversityRules = [
    'snowboard_big_air_best_two' => [
        'requireDistinct' => [
            ['scope' => 'attempts', 'group' => 'Direction', 'minDistinct' => 2],
            ['scope' => 'attempts', 'group' => 'Rotation', 'minDistinct' => 2]
        ]
    ],
    'freeski_big_air_best_two' => [
        'requireDistinct' => [
            ['scope' => 'attempts', 'group' => 'Direction', 'minDistinct' => 2],
            ['scope' => 'attempts', 'group' => 'Rotation', 'minDistinct' => 2]
        ]
    ],
    'kitesurf_big_air' => [
        'requireDistinct' => [
            ['scope' => 'attempts', 'group' => 'Jump', 'minDistinct' => 3]
        ]
    ],
    'kitesurf_freestyle_tricks' => [
        'requireDistinct' => [
            ['scope' => 'attempts', 'group' => 'Jump', 'minDistinct' => 2],
            ['scope' => 'attempts', 'group' => 'Style', 'minDistinct' => 2]
        ],
        'optional' => true
    ],
    'skate_street_hybrid' => [
        'tricksDistinctGroups' => ['Flip', 'Grind/Slide', 'Gap'],
        'minDistinct' => 2
    ],
    'surf_two_best_waves' => [
        'anyPass' => [
            ['group' => 'Wave', 'minDistinct' => 2],
            ['group' => 'Maneuver', 'minDistinct' => 2]
        ]
    ]
];

// Figure dictionaries
$figures = [
    'snowboard' => [
        'Rotation' => ['180', '360', '540', '720', '900', '1080', '1260', '1440', '1620', '1800'],
        'Direction' => ['Frontside', 'Backside', 'Switch FS', 'Switch BS'],
        'Axis' => ['Flat', 'Cork', 'Double Cork', 'Triple Cork'],
        'Grab' => ['Mute', 'Indy', 'Tail', 'Nose', 'Method', 'Stalefish', 'Melon', 'Japan', 'Seatbelt'],
        'Feature' => ['Kicker', 'Rail', 'Box', 'Wallride', 'Hip'],
        'Rail' => ['Boardslide', 'Lipslide', '270 In', '270 Out', '450 Out']
    ],
    'freeski' => [
        'Rotation' => ['180', '360', '540', '720', '900', '1080', '1260', '1440', '1620'],
        'Direction' => ['Left', 'Right', 'Switch L', 'Switch R'],
        'Axis' => ['Flat', 'Cork', 'Double Cork', 'Triple Cork'],
        'Grab' => ['Safety', 'Mute', 'Tail', 'Japan', 'Blunt', 'Nose'],
        'Feature' => ['Kicker', 'Rail', 'Box', 'Wallride', 'Hip']
    ],
    'skateboard' => [
        'Flip' => ['Kickflip', 'Heelflip', 'Varial Flip', 'Hardflip', '360 Flip', 'Impossible'],
        'Grind/Slide' => ['FS 50-50', 'BS 50-50', 'BS Smith', 'FS Smith', 'Crooked', 'Nosegrind', 'Feeble', 'Boardslide', 'Lipslide'],
        'Gap' => ['Ollie', 'Nollie', 'Switch Ollie', '360', 'Shuvit'],
        'Obstacle' => ['Rail', 'Hubba', 'Stairs', 'Ledge', 'Quarter', 'Manual Pad']
    ],
    'bmx' => [
        'Tricks' => ['Barspin', 'Double Bar', 'Tailwhip', 'Double Whip', 'Truckdriver (360 bar)', 'Flair', '720', 'No-Hander', 'Superman', 'Decade', 'Footjam'],
        'Feature' => ['Quarter', 'Box Jump', 'Spine', 'Sub Box', 'Rail', 'Flyout']
    ],
    'inline' => [
        'Grind' => ['Soul', 'Royale', 'Top Soul', 'Top Acid', 'Backslide', 'Makio', 'Fishbrain'],
        'Air' => ['540', '720', '900', 'Alley Oop', 'Switch'],
        'Feature' => ['Rail', 'Box', 'Quarter', 'Spine']
    ],
    'surf' => [
        'Maneuver' => ['Cutback', 'Snap', 'Carve', 'Re-entry', 'Floater', 'Aerial', 'Tube'],
        'Wave' => ['Left', 'Right', 'Closeout', 'Point', 'Beachbreak', 'Reef']
    ],
    'kitesurf' => [
        'Jump' => ['Kiteloop', 'Double Loop', 'Late Backroll', 'Backroll', 'Frontroll', 'Board-off', 'One Foot'],
        'Style' => ['Contraloop', 'Boogie', 'Darkslide', 'Downloop'],
        'Grab' => ['Tail', 'Nose', 'Mute', 'Indy', 'Seatbelt']
    ],
    'parkour' => [
        'Move' => ['Kong', 'Dash', 'Speed Vault', 'Lazy', 'Precision', 'Cat Leap', 'Palm Spin', 'Wall Run', 'Backflip', 'Gainer'],
        'Flow' => ['Link-up', 'Direction Change', 'Stride', 'Bar Combo']
    ],
    'breaking' => [
        'Powermove' => ['Windmill', 'Flare', 'Airflare', 'Headspin', 'Swipe', 'Halo'],
        'Footwork' => ['6-step', 'CCs', 'Zulus', 'Russian', 'Knee Rock'],
        'Freeze' => ['Baby', 'Airchair', 'Hollowback', 'Chair', 'Pike'],
        'Blowup' => ['Combo', 'Thread', 'Power to Freeze']
    ],
    'wakeboard' => [
        'Rail' => ['Front Board', 'Back Board', '270 In', '270 Out', 'Transfer', 'Press'],
        'Air' => ['Tantrum', 'Backroll', 'Raley', 'S-Bend', '540', '720', 'KGB'],
        'Feature' => ['Kicker', 'Rail', 'Funbox', 'Wall']
    ]
];

function seedScoringFormats($pdo, $presets) {
    $pdo->beginTransaction();
    
    try {
        // Clear existing data
        $pdo->exec("DELETE FROM scoring_format_tiebreak");
        $pdo->exec("DELETE FROM scoring_format_flow");
        $pdo->exec("DELETE FROM scoring_format_results");
        $pdo->exec("DELETE FROM scoring_format_criteria");
        $pdo->exec("DELETE FROM scoring_format_rounds");
        $pdo->exec("DELETE FROM scoring_format_mode_config");
        $pdo->exec("DELETE FROM scoring_format_judges");
        $pdo->exec("DELETE FROM scoring_formats");
        
        foreach ($presets as $preset) {
            // Insert main format
            $stmt = $pdo->prepare("
                INSERT INTO scoring_formats (format_id, name, sport, mode) 
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([$preset['id'], $preset['name'], $preset['sport'], $preset['mode']]);
            
            // Insert judge configuration
            $judges = $preset['judges'];
            $scale_type = is_array($judges['scale']) ? 'numeric' : 'custom';
            $scale_min = is_array($judges['scale']) ? $judges['scale'][0] : null;
            $scale_max = is_array($judges['scale']) ? $judges['scale'][1] : null;
            $scale_custom = is_array($judges['scale']) ? null : $judges['scale'];
            $precision = isset($judges['precision']) ? $judges['precision'] : 0;
            
            $stmt = $pdo->prepare("
                INSERT INTO scoring_format_judges 
                (format_id, min_judges, max_judges, scale_min, scale_max, scale_type, scale_custom, precision_decimal, drop_rule) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $preset['id'], $judges['min'], $judges['max'], $scale_min, $scale_max, 
                $scale_type, $scale_custom, $precision, $judges['drop']
            ]);
            
            // Insert mode configuration
            $modeConfigs = [];
            if (isset($preset['sections'])) {
                foreach ($preset['sections'] as $key => $value) {
                    $modeConfigs[] = ['sections', $key, $value];
                }
            }
            if (isset($preset['oi'])) {
                foreach ($preset['oi'] as $key => $value) {
                    $modeConfigs[] = ['oi', $key, $value];
                }
            }
            if (isset($preset['attempts'])) {
                foreach ($preset['attempts'] as $key => $value) {
                    $modeConfigs[] = ['attempts', $key, $value];
                }
            }
            if (isset($preset['runs'])) {
                foreach ($preset['runs'] as $key => $value) {
                    $modeConfigs[] = ['runs', $key, $value];
                }
            }
            if (isset($preset['tricks'])) {
                foreach ($preset['tricks'] as $key => $value) {
                    $modeConfigs[] = ['tricks', $key, $value];
                }
            }
            
            $stmt = $pdo->prepare("
                INSERT INTO scoring_format_mode_config (format_id, config_type, config_key, config_value) 
                VALUES (?, ?, ?, ?)
            ");
            foreach ($modeConfigs as $config) {
                $stmt->execute([$preset['id'], $config[0], $config[1], $config[2]]);
            }
            
            // Insert rounds
            if (isset($preset['rounds'])) {
                $stmt = $pdo->prepare("
                    INSERT INTO scoring_format_rounds (format_id, round_name, runs, aggregation) 
                    VALUES (?, ?, ?, ?)
                ");
                foreach ($preset['rounds'] as $roundName => $roundData) {
                    $stmt->execute([
                        $preset['id'], $roundName, $roundData['runs'], $roundData['agg']
                    ]);
                }
            }
            
            // Insert criteria
            if (isset($preset['criteria'])) {
                $stmt = $pdo->prepare("
                    INSERT INTO scoring_format_criteria (format_id, criteria_type, criteria_name, sort_order) 
                    VALUES (?, ?, ?, ?)
                ");
                foreach ($preset['criteria'] as $type => $criteriaList) {
                    if (is_array($criteriaList)) {
                        foreach ($criteriaList as $index => $criteria) {
                            $stmt->execute([$preset['id'], $type, $criteria, $index]);
                        }
                    } else {
                        // For breaking format which has simple array
                        $stmt->execute([$preset['id'], 'comparative', $criteriaList, 0]);
                    }
                }
            }
            
            // Insert results headers
            if (isset($preset['results']['headers'])) {
                $stmt = $pdo->prepare("
                    INSERT INTO scoring_format_results (format_id, header_name, sort_order) 
                    VALUES (?, ?, ?)
                ");
                foreach ($preset['results']['headers'] as $index => $header) {
                    $stmt->execute([$preset['id'], $header, $index]);
                }
            }
            
            // Insert flow stages
            if (isset($preset['flow'])) {
                $stmt = $pdo->prepare("
                    INSERT INTO scoring_format_flow (format_id, flow_stage, sort_order) 
                    VALUES (?, ?, ?)
                ");
                foreach ($preset['flow'] as $index => $stage) {
                    $stmt->execute([$preset['id'], $stage, $index]);
                }
            }
            
            // Insert tiebreak rules
            if (isset($preset['tiebreak'])) {
                $stmt = $pdo->prepare("
                    INSERT INTO scoring_format_tiebreak (format_id, tiebreak_rule, sort_order) 
                    VALUES (?, ?, ?)
                ");
                foreach ($preset['tiebreak'] as $index => $rule) {
                    $stmt->execute([$preset['id'], $rule, $index]);
                }
            }
        }
        
        $pdo->commit();
        echo "Successfully seeded " . count($presets) . " scoring formats.\n";
        
    } catch (Exception $e) {
        $pdo->rollback();
        echo "Error seeding scoring formats: " . $e->getMessage() . "\n";
    }
}

function seedDiversityRules($pdo, $diversityRules) {
    $pdo->beginTransaction();
    
    try {
        $pdo->exec("DELETE FROM scoring_format_diversity_rules");
        
        $stmt = $pdo->prepare("
            INSERT INTO scoring_format_diversity_rules 
            (format_id, rule_type, scope, group_name, min_distinct, is_optional) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        foreach ($diversityRules as $formatId => $rules) {
            foreach ($rules as $ruleType => $ruleData) {
                if ($ruleType === 'requireDistinct') {
                    foreach ($ruleData as $rule) {
                        $stmt->execute([
                            $formatId, 'requireDistinct', $rule['scope'], 
                            $rule['group'], $rule['minDistinct'], 0
                        ]);
                    }
                } elseif ($ruleType === 'tricksDistinctGroups') {
                    $minDistinct = $rules['minDistinct'] ?? 2;
                    foreach ($ruleData as $group) {
                        $stmt->execute([
                            $formatId, 'tricksDistinctGroups', 'tricks', 
                            $group, $minDistinct, 0
                        ]);
                    }
                } elseif ($ruleType === 'anyPass') {
                    foreach ($ruleData as $rule) {
                        $stmt->execute([
                            $formatId, 'anyPass', null, 
                            $rule['group'], $rule['minDistinct'], 0
                        ]);
                    }
                } elseif ($ruleType === 'optional') {
                    // Update all rules for this format to be optional
                    $updateStmt = $pdo->prepare("
                        UPDATE scoring_format_diversity_rules 
                        SET is_optional = 1 
                        WHERE format_id = ?
                    ");
                    $updateStmt->execute([$formatId]);
                }
            }
        }
        
        $pdo->commit();
        echo "Successfully seeded diversity rules for " . count($diversityRules) . " formats.\n";
        
    } catch (Exception $e) {
        $pdo->rollback();
        echo "Error seeding diversity rules: " . $e->getMessage() . "\n";
    }
}

function seedFigures($pdo, $figures) {
    $pdo->beginTransaction();
    
    try {
        $pdo->exec("DELETE FROM figure_items");
        $pdo->exec("DELETE FROM figure_categories");
        
        $categoryStmt = $pdo->prepare("
            INSERT INTO figure_categories (sport_name, category_name, sort_order) 
            VALUES (?, ?, ?)
        ");
        
        $itemStmt = $pdo->prepare("
            INSERT INTO figure_items (sport_name, category_name, item_name, sort_order) 
            VALUES (?, ?, ?, ?)
        ");
        
        foreach ($figures as $sport => $categories) {
            $categoryOrder = 0;
            foreach ($categories as $categoryName => $items) {
                $categoryStmt->execute([$sport, $categoryName, $categoryOrder++]);
                
                $itemOrder = 0;
                foreach ($items as $item) {
                    $itemStmt->execute([$sport, $categoryName, $item, $itemOrder++]);
                }
            }
        }
        
        $pdo->commit();
        echo "Successfully seeded figures for " . count($figures) . " sports.\n";
        
    } catch (Exception $e) {
        $pdo->rollback();
        echo "Error seeding figures: " . $e->getMessage() . "\n";
    }
}

// Run the seeding
if ($_SERVER['REQUEST_METHOD'] === 'POST' || (isset($argv) && $argv[0])) {
    echo "Starting scoring formats seeding...\n";
    
    seedScoringFormats($pdo, $presets);
    seedDiversityRules($pdo, $diversityRules);
    seedFigures($pdo, $figures);
    
    echo "Seeding completed successfully!\n";
} else {
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Scoring Formats Seeder</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body class="bg-light">
        <div class="container-fluid container-StyleScore p-4">
            <div class="border-0 shadow-none card">
                <div class="border-0 shadow-none card-header">
                    <h4>Scoring Formats Database Seeder</h4>
                </div>
                <div class="border-0 shadow-none card-body">
                    <p>This will populate the database with preset scoring formats, diversity rules, and figure dictionaries.</p>
                    <p><strong>Warning:</strong> This will delete existing scoring format data.</p>
                    
                    <form method="POST">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-database me-2"></i>Seed Database
                        </button>
                        <a href="../dashboard.php" class="btn btn-secondary">
                            <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
                        </a>
                    </form>
                </div>
            </div>
        </div>
    </body>
    </html>
    <?php
}
?>
