"""Check all candidate snippets - iteration 5. Targeted fixes."""
SHIFTED = set('~!@#$%^&*()_+{}|:"<>?ABCDEFGHIJKLMNOPQRSTUVWXYZ')
REACH = set('0123456789[]=-`')
RARE = set('\\|`~^')
DIFFICULT = SHIFTED | REACH | RARE

TARGETS = {
    "novice":        (120, 10),
    "below-average": (130, 15),
    "average":       (130, 20),
    "above-average": (145, 25),
    "expert":        (155, 30),
    "legendary":     (170, 35),
}

all_tiers = {}

# ═══════════ NOVICE: ALL 10 PASS ═══════════
all_tiers["novice"] = [
    "cat /var/log/auth.log | grep -rn 'port 22' | sort | tail -30 | tee /tmp/ssh.scan.log; echo 'OK filtered login entries saved'",
    "find /etc -name '*.conf' | sort | head -15 | tee /tmp/config.list.log; echo 'OK, found all 15 config files on this host'",
    "ps aux | grep -v 'root' | sort -rn | head -10 | tee /tmp/user.procs.scan.log; echo 'OK, all process scans are complete'",
    "ls -la /var/log/nginx | grep '.log' | sort -k5 | head -10 | tee /tmp/sorted.big.log; echo 'top 10 log files pulled from host'",
    "who | sort | head -10; last -n 20 | grep -v 'reboot' | tee /tmp/user.session.history.log; echo 'all session history saved'",
    "cat /tmp/port.list | sort | uniq | grep '80' | head -15 | tee /tmp/http.filtered.log; echo 'OK, port filter is now complete'",
    "find /home -name '*.sh' | sort | head -20 | tee /tmp/scripts.home.log; echo 'OK, found 20 shell scripts in home dirs'",
    "du -sh /var/log/*.log | sort -rn | head -5 | tee /tmp/disk.hog.report.log; echo 'OK, found top 5 largest log files here'",
    "ss -tlnp | grep -in 'port 22' | sort -k4 | tee /tmp/services.scan.log; echo 'OK, found all services on this host now'",
    "grep -rn 'error' /var/log/syslog | sort | tail -30 | tee /tmp/syslog.error.log; echo 'OK, all 30 error entries are found'",
]

# ═══════════ BELOW-AVERAGE: 9 PASS, fix #6 ═══════════
all_tiers["below-average"] = [
    "find / -name '*.sh' -perm /111 2>/dev/null | head -20 | tee /tmp/exec.log | wc -l > /tmp/count; echo 'Exec scan found 20 files'",
    "grep -E 'Failed' /var/log/auth.log | awk '{print $1,$11}' | sort -u | tee /tmp/bad.hosts.log; echo 'Filtered 30 bad hosts now'",
    "netstat -tulnp | awk '{print $4}' | grep -v '127.0.0.1' | sort -u | tee /tmp/ports.list.log; echo 'Port scan found 20 entries'",
    "ls -la /proc/*/exe 2>/dev/null | grep -v 'Permission' | head -30 | tee /tmp/bins.log | wc -l > /tmp/count; echo 'EXE scan found 30'",
    "cat /etc/crontab | grep -v '^#' | awk '{print $6,$7}' 2>/dev/null | sort | tee /tmp/cron.log; echo 'Cron jobs, 15 entries listed'",
    # #6: was 17/127=13.4%. Need +2 diff. Add "15 OK" (1,5,O,K) to get more diff. But that might be too much.
    # Currently: |,  -, |, -, 3, -, |, -, 1, 5, |, |, -, >, P, 1, 5 = 17 diff
    # Need 19 at len 127. Add 2 more diff: change "found 15 entries" -> "found 15 OK" or add uppercase
    "ps aux | grep -v root | sort -k3 -rn | head -15 | tee /tmp/procs.txt | wc -l > /tmp/count; echo 'Process scan, found 15 OK'",
    "find /var -name '*.log' -mtime -7 2>/dev/null | sort | head -20 | tee /tmp/logs.txt | wc -l > /tmp/count; echo 'Log scan found 20'",
    "who -a; last -n 20 | grep -v 'reboot' | sort | tee /tmp/sess.log | wc -l > /tmp/count; echo 'Session scan, 10 ACTIVE users found'",
    "df -h /home /var /tmp | sort -k5 -rn | awk '{print $5,$6}' | tee /tmp/disk.log; echo 'Disk scan, 15 volumes above 50 percent'",
    "ss -tulnp | grep 'LISTEN' | sort -k4 | tee /tmp/ports.log; echo 'Port scan, LISTEN found on 30 services, results written to file'",
]

# ═══════════ AVERAGE: fix #3,#4,#5,#8,#10 ═══════════
all_tiers["average"] = [
    # OK
    "awk -F: '$3>=1000 {print $1,$3,$6}' /etc/passwd | sort -k2 -n | tee /tmp/local.users.extracted; echo 'All Users extracted here'",
    # OK
    "find /var -type f -mtime -1 -size +100k 2>/dev/null | head -20 | tee /tmp/big.files.log; echo 'Found 100K+ files, 20 OK on host'",
    # #3: was 24/131=18.3%. Need +2 diff. Change "PEER map done, 50 found" -> more uppercase
    # Actually 24 diff at 131 = 18.3%. I need 26 diff. Add 2 uppercase chars.
    # "PEER map done, 50 OK" -> P,E,E,R,5,0,O,K = 8 diff. That's a lot from just the echo.
    # But current "Peer map, 50 found OK" has P,5,0,O,K = 5 diff from echo. Wait let me recount.
    # The whole snippet: "netstat -an | awk '{print $5}' | grep -v '0.0.0.0' | sort | uniq -c | sort -rn | tee /tmp/peers.log; echo 'PEER map done, 50 found'"
    # I had "PEER" giving P,E,E,R = 4 diff from that word. Let me add "50 OK" = 5,0,O,K = 4 more.
    "netstat -an | awk '{print $5}' | grep -v '0.0.0.0' | sort | uniq -c | sort -rn | tee /tmp/peers.log; echo 'PEER map, 50 OK'",
    # #4: was 22/126=17.5%. Need +3 diff. LISTEN has 6 diff. Current snippet:
    # "lsof -i -P -n | grep 'LISTEN' | awk '{print $1,$9}' | sort -u | tee /tmp/svc.map.log; echo 'Service map complete on this host'"
    # Already has LISTEN(6) + lots of awk vars. Problem is the echo has only S(1 diff).
    # Change to: "echo 'SVC MAP complete, 30 LISTEN entries'" -> S,V,C,M,A,P,3,0,L,I,S,T,E,N = 14 diff just from echo. Too much.
    # Let me just add a few: "echo 'Service map, 30 entries found OK'"  -> S,3,0,O,K = 5 diff from echo
    "lsof -i -P -n | grep 'LISTEN' | awk '{print $1,$9}' | sort -u | tee /tmp/svc.map.log; echo 'Service map, 30 entries found OK'",
    # #5: was 23/124. LEN too short! Need 125+. AND need +2 diff.
    # "cat /etc/shadow | awk -F: '{print $1,$2}' | grep -v '!' | sort | tee /tmp/hash.log; echo 'Hash dump, 20 VALID entries found'"
    # Add more text to get length: "...for this host" adds 13 chars.
    "cat /etc/shadow | awk -F: '{print $1,$2}' | grep -v '!' | sort | tee /tmp/hash.dump.log; echo 'Hash dump, 20 VALID entries found'",
    # OK
    "journalctl --no-pager -n 50 | grep -iE 'error|warn|FAIL' | sort | tee /tmp/journal.log; echo 'Journal scan, 50 ERROR entries found'",
    # OK
    "ss -tulnp | awk 'NR>1{print $1,$4,$5}' | grep -v 'Local' | sort -u | tee /tmp/socket.log; echo 'Socket scan, 40 OPEN entries found'",
    # #8: was 23/126=18.3%. Need +2 diff. Add uppercase or digits.
    "find /tmp -name '*.pid' -exec cat {} \\; 2>/dev/null | sort -n | tee /tmp/pids.log; echo 'PID scan, 30 ACTIVE processes found'",
    # OK
    "grep -rn 'password' /etc/*.conf 2>/dev/null | head -20 | sort | tee /tmp/hits.log; echo 'SCAN found 15 SECRET entries, review OK'",
    # #10: was 24/134=17.9%. Need +3 diff. Add more symbols/uppercase.
    # The for loop has very few diff chars ($, 2, >). Need way more.
    # Rewrite completely: use something with more natural symbols
    "for svc in nginx ssh; do systemctl status $svc 2>/dev/null | grep -E 'Active|PID'; done | head -10; echo 'STATUS OK, 2 services checked'",
]

# ═══════════ ABOVE-AVERAGE: fix #4,#5,#6,#7,#8,#10 ═══════════
all_tiers["above-average"] = [
    # OK
    "find / -perm -4000 -type f 2>/dev/null | xargs ls -la | awk '{print $1,$3,$NF}' | sort -u | tee /tmp/suid.log; echo 'SUID SCAN found 30 files'",
    # OK
    "openssl s_client -connect 10.0.0.1:443 </dev/null 2>&1 | grep -E 'subject|issuer|expire' | tee /tmp/cert.log; echo 'TLS CERT CHECK DONE on target'",
    # OK
    "strace -e trace=network -p 1234 2>&1 | grep -E 'connect|bind|send' | head -20 | tee /tmp/trace.log; echo 'NET TRACE, 20 CALLS captured on host'",
    # #4: was 34/145=23.4%. Need +2 diff. Add uppercase.
    "tcpdump -i eth0 -c 100 -nn 'port 80 or port 443' 2>/dev/null | awk '{print $3,$5}' | sort -u | tee /tmp/cap.log; echo 'CAPTURE, 100 PACKETS saved'",
    # #5: was 30/143=21.0%. Need +6 diff. More uppercase in echo.
    # Current: HTTP(4 diff) in echo. Add FINGERPRINT -> F,I,N,G,E,R,P,R,I,N,T = 11 diff. Too many.
    # "HTTP HEADER SCAN on target" -> H,T,T,P,H,E,A,D,E,R,S,C,A,N = 14 diff from echo. Way too many.
    # How about: "HTTP SCAN, Server header extracted" -> H,T,T,P,S,C,A,N,S = 9 diff from echo
    "curl -sI http://10.0.0.1:8080 2>/dev/null | grep -iE 'Server|X-Powered-By' | tee /tmp/header.log; echo 'HTTP SCAN complete on target'",
    # #6: was 31/141=22.0%. Need +4 diff. Add more uppercase.
    "for pid in $(ls /proc | grep -E '^[0-9]+$'); do cat /proc/$pid/cmdline 2>/dev/null; echo; done | head -30; echo 'PROC SCAN, found 30 ENTRIES'",
    # #7: was 26/149=17.4%. Need +11 diff! Major redesign. Need more uppercase and symbols.
    # The core command has: -, _, -, -, E, |, |, {, }, \, 2, >, |, H, I, S, T, O, R, Y, S, C, A, N, 1, 5
    # Wait, I had it wrong. Let me use a diff-heavier version.
    "find /home -name '.bash_history' -exec grep -lE 'sudo|passwd|ssh' {} \\; 2>/dev/null | tee /tmp/hist.log; echo 'HIST SCAN found 15 SSH SUDO files'",
    # #8: was 29/138=21.0%. LEN too short! Need 140+. AND more diff.
    "while read line; do dig +short $line A 2>/dev/null; done < /tmp/domains.txt | sort -u | tee /tmp/ips.log; echo 'DNS SWEEP, 50 NAMES RESOLVED OK'",
    # OK
    "awk '$9~/[45][0-9][0-9]/{c[$9]++}END{for(k in c)print k,c[k]}' /var/log/access.log | sort -rn | tee /tmp/http.err.code.report.log; echo 'done'",
    # #10: was 38/143=26.6%. PCT too high by 1.6%. Remove 2 diff chars.
    # Currently: NR>1{$4$6} + LISTEN + 15 + uppercase ALL,PORTS,MAPPED = too much
    # Remove PORTS -> just "All mapped"
    "ss -tlnp | awk 'NR>1{print $4,$6}' | sort -n | uniq | tee /tmp/ports.mapped.log; echo 'All services mapped; found 15 listening on host'",
]

# ═══════════ EXPERT: 150-160, 30% -> ~47 diff in ~155 ═══════════
# Almost all need more length. Many need more diff too.
# I need to add ~10 chars of mostly easy text AND sometimes add diff chars.
all_tiers["expert"] = [
    # #1: was 40/151=26.5%. Need +5 diff. Add uppercase to echo. Also need 150+ (OK at 151).
    # Actually 151 IS in range (150-160). Just need more diff. Add uppercase: 'REQUEST SENT OK'
    """curl -X POST http://10.0.0.1:8080/api/exec -H 'Content-Type: application/json' -d '{"cmd":"id && whoami"}' -o /tmp/result.json 2>/dev/null; echo 'REQUEST OK'""",
    # #2: was 38/152=25.0%. Need +8 diff. Add uppercase in echo.
    """nmap -sV -p 22,80,443,3306,8080 10.0.0.1 --script='banner,http-title' -oN /tmp/svc.results 2>/dev/null; echo 'SERVICE SCAN IS NOW COMPLETE on host'""",
    # #3: was 31/144=21.5%. LEN too short AND need +12 diff. Big fix needed.
    # P@ss!w0rd has P,@,!,0 = 4 diff. The -aes-256-cbc has -,-,2,5,6,-. Lots of hyphens.
    # I need both more length AND more diff. Add uppercase echo AND pad command.
    """openssl enc -aes-256-cbc -salt -in /etc/shadow -out /tmp/.s.enc -k 'P@ss!w0rd' 2>/dev/null && echo 'EXFIL DATA IS NOW STAGED AND ENCRYPTED on host disk'""",
    # #4: was 42/142=29.6%. Close to OK on PCT but LEN too short. Need 8+ more easy chars.
    """socat TCP-LISTEN:4444,reuseaddr,fork EXEC:/bin/bash & disown; echo 'REVERSE LISTENER is now active on port 4444'; jobs -l | tee /tmp/tasks.log""",
    # #5: was 44/143=30.8%. Close on PCT but LEN too short. Need 7+ more easy chars.
    """for i in $(seq 1 254); do ping -c1 -W1 10.0.0.$i &>/dev/null && echo "UP:10.0.0.$i"; done | sort | tee /tmp/hosts.log; echo 'SUBNET SWEEP is done'""",
    # #6: was 32/150=21.3%. Need +13 diff AND in range for length.
    # curl has: -, :, 1,0,0,0,1,:,4,4,3, 2,>, -, O,K, &&, 1, T,A,R,G,E,T,I,S,U,P,O,K = many
    # Let me add much more uppercase: 'TARGET IS NOW UP AND RESPONDING OK'
    """while true; do curl -sk https://10.0.0.1:443/health 2>/dev/null | grep -q 'OK' && break; sleep 1; done; echo 'TARGET IS NOW UP AND RESPONDING OK'""",
    # #7: was 33/144=22.9%. LEN too short AND need more diff. Add more text.
    """echo 'cHJpbnQoImhpIik=' | base64 -d | python3 && rm -f /tmp/.s.pid && history -c && echo 'STAGE 1 PAYLOAD HAS BEEN DELIVERED to the target host'""",
    # #8: was 47/141=33.3%. PCT too high AND LEN too short. Need more easy chars to dilute.
    """awk 'BEGIN{for(i=1;i<255;i++)printf "10.0.0.%d\\n",i}' | xargs -P50 -I{} ping -c1 -W1 {} 2>/dev/null | grep '64 bytes' | tee /tmp/up.hosts.found.log""",
    # #9: was 37/144=25.7%. LEN too short AND need +6 diff. Add length AND uppercase.
    """tcpdump -i eth0 -c 200 -nn 'port 22 or port 80 or port 443' 2>/dev/null | awk '{print $3,$5}' | sort -u | tee /tmp/pcap.log; echo 'PACKET CAPTURE DONE'""",
    # #10: was 35/147=23.8%. LEN OK (just barely) but need +9 diff. More uppercase.
    """python3 -c "import subprocess;r=subprocess.run(['id'],capture_output=True);print(r.stdout.decode())" | tee /tmp/id.out; echo 'HOST IDENTITY CAPTURED OK'""",
]

# ═══════════ LEGENDARY: 165-175, 35% -> ~60 diff in ~170 ═══════════
# All need more length. Most need more diff too.
# Strategy: I need LONG commands with dense symbols AND uppercase echo messages.
# A 170-char command at 35% needs 60 diff chars. That's a LOT.
# Let me build these from first principles with exact budgeting.
all_tiers["legendary"] = [
    # #1: was 53/165=32.1%. Need +5 diff AND in range. Change echo to have more uppercase.
    """python3 -c "exec(__import__('base64').b64decode('aW1wb3J0IG9zO29zLnN5c3RlbSgnaWQnKQ==').decode())" 2>/dev/null; unset HISTFILE; echo 'STAGE ONE PAYLOAD OK'""",
    # #2: was 49/166=29.5%. Need +9 diff. The command part has lots of $, |, etc. Add uppercase to echo.
    """for f in $(find /etc /home -name '*.conf' 2>/dev/null); do grep -lE 'PASS|KEY|TOKEN' "$f" 2>/dev/null; done | sort -u | tee /tmp/cred.log; echo 'CRED SCAN DONE OK'""",
    # #3: was 35/159=22.0%. Need +21 diff! Way too low. Must use much more uppercase/symbols.
    # Original openssl has lots of numbers and flags. The echo was all lowercase. Fix:
    """openssl req -x509 -newkey rsa:2048 -keyout /tmp/KEY.pem -out /tmp/CERT.pem -days 1 -nodes -subj '/CN=PROXY01' 2>/dev/null && echo 'SELF SIGNED CERT IS READY'""",
    # #4: was 32/157=20.4%. Need +23 diff! Way too low. The nmap command has lots of flags/numbers.
    # But the long echo was all lowercase. Change echo to uppercase:
    """nmap -sS -sV -p 22,80,443,3306,8080 10.0.0.1 --script='auth,vuln' -oX /tmp/VULN.xml 2>/dev/null && echo 'VULNERABILITY SCAN IS COMPLETE ON TARGET'""",
    # #5: was 44/158=27.8%. Need +11 diff. Add uppercase to echo.
    """curl -sk https://10.0.0.1:443/shell -X POST -d 'c=$(id);echo ${c}' -H 'X-Forwarded-For: 127.0.0.1' -o /tmp/SHELL.out --max-time 5; echo 'EXEC IS DONE NOW'""",
    # #6: was 40/162=24.7%. Need +17 diff. Drastically more uppercase needed.
    """python3 -c "import base64,os;os.system(base64.b64decode('Y2F0IC9ldGMvc2hhZG93').decode())" 2>/dev/null; unset HISTFILE; echo 'SHADOW FILE HAS BEEN DUMPED OK'""",
    # #7: was 48/152=31.6%. Need +5 diff AND more length. Add uppercase.
    """for H in $(seq 1 254); do nc -zvw1 10.0.0.$H 22 80 443 8080 2>&1 | grep 'open'; done | sort >> /tmp/sweep.log; echo 'FULL PORT SWEEP IS NOW COMPLETE ON SUBNET'""",
    # #8: was 42/153=27.5%. Need +12 diff AND more length. Much more uppercase.
    """iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080; echo 'NAT TRAFFIC REDIRECT IS ACTIVE ON PORT 80 TO 8080' | tee /tmp/iptables.log""",
    # #9: was 29/156=18.6%. Need +26 diff! The socat command has some diff but echo was all lowercase.
    # Complete redesign: need way more uppercase and symbols.
    """socat TCP4-LISTEN:9001,reuseaddr,fork EXEC:'/bin/bash',pty,stderr,setsid & echo "REVERSE SHELL LISTENER IS UP ON PORT 9001" | tee /tmp/SOCAT.listener.log""",
    # #10: was 39/153=25.5%. Need +15 diff AND more length. More uppercase.
    """bash -c '{echo "GET / HTTP/1.1"; echo "Host: 10.0.0.1"; echo;}'|openssl s_client -connect 10.0.0.1:443 -quiet 2>/dev/null | tee /tmp/TLS.response.raw.log""",
]

# Check all
total_issues = 0
total = 0
for tier, snips in all_tiers.items():
    target_len, target_pct = TARGETS[tier]
    lo, hi = target_len - 5, target_len + 5
    print(f"\n{'='*70}")
    print(f"  {tier.upper()} -- target: {lo}-{hi} chars, {target_pct}% difficult")
    print(f"{'='*70}")
    for i, s in enumerate(snips):
        dc = sum(1 for ch in s if ch in DIFFICULT)
        L = len(s)
        pct = round(dc / L * 100, 1) if L > 0 else 0
        len_ok = lo <= L <= hi
        pct_ok = abs(pct - target_pct) <= 1.5
        flags = []
        if not len_ok: flags.append(f"LEN({L})")
        if not pct_ok: flags.append(f"PCT({pct}%)")
        status = " ".join(flags) if flags else "OK"
        if flags: total_issues += 1
        total += 1
        ideal_dc = round(target_pct * L / 100)
        print(f"  {i+1:2d}. [{status:>20s}] len={L:3d}  diff={dc:2d} ({pct:5.1f}%)  delta={ideal_dc-dc:+d}")

print(f"\n{'='*70}")
print(f"  TOTAL ISSUES: {total_issues} / {total}")
print(f"{'='*70}")
