const db = require('../db');

async function createBatch3() {
    try {
        console.log('🚀 Batch 3: Command Line Mastery\n');

        const cmdLessons = [
            {
                id: 47,
                title: 'Advanced grep',
                content: `# Advanced grep Techniques

Master text searching for log analysis and investigation.

## Basic Syntax
\`\`\`bash
grep "pattern" file.txt
\`\`\`

## Essential Flags

**-i** Case-insensitive
\`\`\`bash
grep -i "error" log.txt
\`\`\`

**-v** Invert (show lines NOT matching)
\`\`\`bash
grep -v "success" log.txt
\`\`\`

**-n** Show line numbers
\`\`\`bash
grep -n "failed" auth.log
\`\`\`

**-r** Recursive search
\`\`\`bash
grep -r "malware" /var/log/
\`\`\`

**-c** Count matches
\`\`\`bash
grep -c "login" access.log
\`\`\`

**-A** After context (lines after match)
**-B** Before context
**-C** Context (before + after)
\`\`\`bash
grep -A 3 "ERROR" app.log
grep -C 5 "failed login" auth.log
\`\`\`

## SOC Use Cases

**Find failed logins:**
\`\`\`bash
grep "Failed password" /var/log/auth.log
\`\`\`

**Multiple patterns:**
\`\`\`bash
grep -E "error|warning|critical" system.log
\`\`\`

**Exclude noise:**
\`\`\`bash
grep "error" app.log | grep -v "benign"
\`\`\`

**Count unique IPs:**
\`\`\`bash
grep "Failed" auth.log | awk '{print $11}' | sort | uniq -c
\`\`\`

## Pro Tips
✓ Use quotes for patterns with spaces
✓ Combine with other tools (pipe |)
✓ Save results: grep "pattern" file > results.txt
✓ Use -E for extended regex`,
                questions: [
                    ['Case-insensitive flag?', '-i', 'Ignore case'],
                    ['Show line numbers?', '-n', 'Number lines'],
                    ['Recursive search?', '-r', 'All directories'],
                    ['Invert match?', '-v', 'NOT containing'],
                    ['Count matches?', '-c', 'Total occurrences']
                ]
            },
            {
                id: 48,
                title: 'sed Basics',
                content: `# sed - Stream Editor

Edit text files from command line.

## Basic Syntax
\`\`\`bash
sed 's/old/new/' file.txt
\`\`\`

## Substitute Command

**Replace first occurrence:**
\`\`\`bash
sed 's/error/ERROR/' log.txt
\`\`\`

**Replace all occurrences (g flag):**
\`\`\`bash
sed 's/http/https/g' urls.txt
\`\`\`

**Case-insensitive (I flag):**
\`\`\`bash
sed 's/error/ERROR/gI' log.txt
\`\`\`

## Line Operations

**Delete lines:**
\`\`\`bash
sed '/^$/d' file.txt          # Delete empty lines
sed '/pattern/d' file.txt     # Delete matching lines
sed '1d' file.txt             # Delete first line
\`\`\`

**Print specific lines:**
\`\`\`bash
sed -n '5,10p' file.txt       # Lines 5-10
sed -n '/error/p' log.txt     # Lines with "error"
\`\`\`

## In-Place Editing
\`\`\`bash
sed -i 's/old/new/g' file.txt    # Linux
sed -i '' 's/old/new/g' file.txt # macOS
\`\`\`

## SOC Use Cases

**Clean logs:**
\`\`\`bash
sed 's/^[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}/REDACTED/g' access.log
\`\`\`

**Extract timestamps:**
\`\`\`bash
sed -n 's/.*\\([0-9]\\{2\\}:[0-9]\\{2\\}:[0-9]\\{2\\}\\).*/\\1/p' log.txt
\`\`\`

**Remove comments:**
\`\`\`bash
sed '/^#/d' config.txt
\`\`\``,
                questions: [
                    ['sed full name?', 'Stream Editor', 'Text processor'],
                    ['Substitute command?', 's', 'Replace text'],
                    ['Replace all flag?', 'g', 'Global'],
                    ['In-place edit flag?', '-i', 'Modify file'],
                    ['Delete line command?', 'd', 'Remove']
                ]
            },
            {
                id: 49,
                title: 'awk Programming',
                content: `# awk Programming Basics

Powerful text processing language.

## Basic Syntax
\`\`\`bash
awk 'pattern {action}' file.txt
\`\`\`

## Print Columns

**Print first column:**
\`\`\`bash
awk '{print $1}' file.txt
\`\`\`

**Print multiple columns:**
\`\`\`bash
awk '{print $1, $3}' access.log
\`\`\`

**Print last column:**
\`\`\`bash
awk '{print $NF}' file.txt
\`\`\`

## Field Separator
\`\`\`bash
awk -F: '{print $1}' /etc/passwd    # Use : as separator
awk -F',' '{print $2}' data.csv     # Use , for CSV
\`\`\`

## Patterns

**Match pattern:**
\`\`\`bash
awk '/error/ {print}' log.txt
\`\`\`

**Conditional:**
\`\`\`bash
awk '$3 > 100 {print $1, $3}' data.txt
\`\`\`

## Built-in Variables
- **NR** - Line number
- **NF** - Number of fields
- **$0** - Entire line

## SOC Use Cases

**Count IPs:**
\`\`\`bash
awk '{print $1}' access.log | sort | uniq -c | sort -rn
\`\`\`

**Failed logins:**
\`\`\`bash
awk '/Failed/ {print $9, $11}' auth.log
\`\`\`

**Sum values:**
\`\`\`bash
awk '{sum += $3} END {print sum}' data.txt
\`\`\`

**Filter by time:**
\`\`\`bash
awk -F: '$1 >= 14 && $1 <= 18' timestamps.log
\`\`\``,
                questions: [
                    ['First column variable?', '$1', 'Field one'],
                    ['Line number variable?', 'NR', 'Number of Records'],
                    ['Field separator flag?', '-F', 'Delimiter'],
                    ['Last field variable?', '$NF', 'Number of Fields'],
                    ['Entire line variable?', '$0', 'Full record']
                ]
            },
            {
                id: 50,
                title: 'Regular Expressions',
                content: `# Regular Expressions (Regex)

Pattern matching language for text.

## Basic Patterns

**.** - Any single character
\`\`\`bash
grep "h.t" file.txt     # Matches: hat, hit, hot
\`\`\`

**^** - Start of line
**$** - End of line
\`\`\`bash
grep "^Error" log.txt   # Lines starting with Error
grep "done$" log.txt    # Lines ending with done
\`\`\`

***** - Zero or more
**+** - One or more
**?** - Zero or one
\`\`\`bash
grep "erro*r" log.txt   # error, errror, errrror
grep "a+" file.txt      # a, aa, aaa
\`\`\`

## Character Classes

**[abc]** - Any of a, b, or c
**[^abc]** - NOT a, b, or c
**[a-z]** - Any lowercase letter
**[0-9]** - Any digit

\`\`\`bash
grep "[Ee]rror" log.txt        # Error or error
grep "[0-9]{1,3}" file.txt     # 1-3 digits
\`\`\`

## Special Characters

**\\d** - Digit [0-9]
**\\w** - Word character [a-zA-Z0-9_]
**\\s** - Whitespace

## Quantifiers

**{n}** - Exactly n times
**{n,}** - At least n times
**{n,m}** - Between n and m times

\`\`\`bash
grep -E "[0-9]{3}-[0-9]{4}" contacts.txt  # Phone: 555-1234
\`\`\`

## SOC Examples

**IP Address:**
\`\`\`bash
grep -E "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}" log.txt
\`\`\`

**Email:**
\`\`\`bash
grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}" emails.txt
\`\`\`

**URL:**
\`\`\`bash
grep -E "https?://[^\\s]+" logs.txt
\`\`\``,
                questions: [
                    ['Any character?', '.', 'Wildcard'],
                    ['Start of line?', '^', 'Beginning anchor'],
                    ['End of line?', '$', 'Ending anchor'],
                    ['One or more?', '+', 'Quantifier'],
                    ['Digit pattern?', '\\d', 'Number character']
                ]
            },
            {
                id: 51,
                title: 'Bash Scripting',
                content: `# Bash Scripting Intro

Automate SOC tasks with shell scripts.

## Shebang
\`\`\`bash
#!/bin/bash
\`\`\`

## Variables
\`\`\`bash
NAME="Alice"
echo "Hello $NAME"

# Command substitution
DATE=$(date +%Y-%m-%d)
FILES=$(ls -l | wc -l)
\`\`\`

## Conditionals
\`\`\`bash
if [ $STATUS -eq 0 ]; then
    echo "Success"
else
    echo "Failed"
fi
\`\`\`

## Loops
\`\`\`bash
# For loop
for file in *.log; do
    echo "Processing $file"
done

# While loop
while read line; do
    echo "$line"
done < input.txt
\`\`\`

## Functions
\`\`\`bash
check_service() {
    if systemctl is-active $1; then
        echo "$1 is running"
    fi
}

check_service nginx
\`\`\`

## SOC Script Examples

**Log analyzer:**
\`\`\`bash
#!/bin/bash
LOG="/var/log/auth.log"
echo "Failed logins today:"
grep "Failed password" $LOG | wc -l
\`\`\`

**IP blocker:**
\`\`\`bash
#!/bin/bash
for IP in $(cat suspicious_ips.txt); do
    iptables -A INPUT -s $IP -j DROP
    echo "Blocked $IP"
done
\`\`\`

**Health check:**
\`\`\`bash
#!/bin/bash
if ! ping -c 1 8.8.8.8 > /dev/null; then
    echo "Network down!" | mail -s "Alert" admin@example.com
fi
\`\`\``,
                questions: [
                    ['Script first line?', '#!/bin/bash', 'Shebang'],
                    ['Variable prefix?', '$', 'Dollar sign'],
                    ['Command substitution?', '$()', 'Execute command'],
                    ['String equality test?', '=', 'Compare strings'],
                    ['Read file loop?', 'while read', 'Line by line']
                ]
            },
            {
                id: 52,
                title: 'Pipes & Redirection',
                content: `# Pipes & Redirection

Chain commands and manage output.

## Pipe (|)
Send output of one command to another

\`\`\`bash
cat file.txt | grep "error" | wc -l
ps aux | grep nginx
netstat -an | grep ESTABLISHED
\`\`\`

## Redirection

**>** - Overwrite file
\`\`\`bash
echo "Hello" > file.txt
ls -l > listing.txt
\`\`\`

**>>** - Append to file
\`\`\`bash
echo "New line" >> file.txt
date >> log.txt
\`\`\`

**<** - Input from file
\`\`\`bash
wc -l < file.txt
mysql < database.sql
\`\`\`

**2>** - Redirect errors
**2>&1** - Errors to same as output
\`\`\`bash
command 2> errors.log
command > output.txt 2>&1
command &> all.log        # Both stdout and stderr
\`\`\`

## /dev/null
Discard output

\`\`\`bash
command > /dev/null 2>&1     # Silent execution
\`\`\`

## SOC Examples

**Failed login analysis:**
\`\`\`bash
grep "Failed" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn > failed_ips.txt
\`\`\`

**Error summary:**
\`\`\`bash
grep -i error /var/log/*.log | cut -d: -f1 | uniq -c > error_summary.txt
\`\`\`

**Live monitoring:**
\`\`\`bash
tail -f /var/log/syslog | grep --line-buffered "error"
\`\`\``,
                questions: [
                    ['Chain commands?', '|', 'Pipe'],
                    ['Overwrite file?', '>', 'Redirect output'],
                    ['Append to file?', '>>', 'Add to end'],
                    ['Discard output?', '/dev/null', 'Black hole'],
                    ['Redirect errors?', '2>', 'stderr']
                ]
            },
            {
                id: 53,
                title: 'CLI Efficiency',
                content: `# Command Line Efficiency

Work faster in the terminal.

## Shortcuts

**Ctrl+C** - Cancel current command
**Ctrl+D** - Exit/Logout
**Ctrl+Z** - Suspend process
**Ctrl+L** - Clear screen
**Ctrl+A** - Beginning of line
**Ctrl+E** - End of line
**Ctrl+U** - Clear line before cursor
**Ctrl+K** - Clear line after cursor
**Ctrl+R** - Search history

## History
\`\`\`bash
history                       # Show command history
!number                       # Run command number
!!                           # Repeat last command
!$                           # Last argument of previous command
\`\`\`

## Aliases
\`\`\`bash
alias ll='ls -lah'
alias grep='grep --color=auto'
alias alert='grep -i "error\\|warning\\|critical"'
\`\`\`

Add to ~/.bashrc for persistence

## Tab Completion
- Press TAB to autocomplete
- Double TAB to show options

## Background Jobs
\`\`\`bash
command &                     # Run in background
jobs                          # List background jobs
fg                            # Bring to foreground
bg                            # Resume in background
\`\`\`

## Screen/Tmux
Keep sessions alive

\`\`\`bash
screen -S mysession          # Create session
Ctrl+A D                     # Detach
screen -r mysession          # Reattach
\`\`\`

## SOC Efficiency Tips
✓ Create aliases for common searches
✓ Use history search (Ctrl+R)
✓ Save frequent commands as scripts
✓ Use screen for monitoring
✓ Master keyboard shortcuts`,
                questions: [
                    ['Clear screen?', 'Ctrl+L', 'Terminal shortcut'],
                    ['Search history?', 'Ctrl+R', 'Reverse search'],
                    ['Repeat last command?', '!!', 'Bang bang'],
                    ['Last argument?', '!$', 'Previous param'],
                    ['Run in background?', '&', 'Ampersand']
                ]
            }
        ];

        for (const lesson of cmdLessons) {
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [lesson.id, lesson.content, 'markdown', 8]);

            for (let i = 0; i < lesson.questions.length; i++) {
                const q = lesson.questions[i];
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)',
                    [lesson.id, q[0], q[1], i + 1, q[2], 0]);
            }
            console.log(`✓ ${lesson.title}`);
        }

        console.log(`\n✅ Command Line Mastery complete! (${cmdLessons.length} lessons)`);
        console.log('\n🎉 PATH 1 FULLY COMPLETE! (45 lessons total)\n');

        const totalLessons = await db.query('SELECT COUNT(*) as count FROM lesson_content');
        console.log(`Total lessons in platform: ${totalLessons.rows[0].count}/348\n`);

        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

createBatch3();
