import re

SYMBOLS = set('~!@#$%^&*()_+{}|:"<>?[]=-`\\/;.,')

def is_mixed_case_upper(s, i):
    """Check if uppercase letter at position i is in a mixed-case word."""
    c = s[i]
    if c < 'A' or c > 'Z':
        return False
    # Check if any adjacent letter is lowercase
    if i > 0 and s[i-1].islower():
        return True
    if i < len(s)-1 and s[i+1].islower():
        return True
    # Check the whole word for mixed case
    start = i
    while start > 0 and s[start-1].isalpha():
        start -= 1
    end = i
    while end < len(s)-1 and s[end+1].isalpha():
        end += 1
    word = s[start:end+1]
    has_upper = any(c.isupper() for c in word)
    has_lower = any(c.islower() for c in word)
    return has_upper and has_lower

def diff_count(s):
    count = 0
    for i, c in enumerate(s):
        if c in SYMBOLS:
            count += 1
        elif c.isupper() and is_mixed_case_upper(s, i):
            count += 1
    return count

TARGETS = {
    "trivial": 0, "novice": 2, "below-average": 7,
    "average": 10, "above-average": 13, "expert": 17, "legendary": 21,
}
TLENS = {
    "trivial": 110, "novice": 122, "below-average": 136,
    "average": 148, "above-average": 160, "expert": 172, "legendary": 185,
}

with open("scripts/games/CodeEntry.js", encoding="utf-8") as f:
    src = f.read()

tier_keys = ["trivial", "novice", '"below-average"', "average", '"above-average"', "expert", "legendary"]

for key in tier_keys:
    clean = key.strip('"')
    target = TARGETS[clean]
    tlen = TLENS[clean]

    pat = re.compile(re.escape(key) + r'\s*:\s*\[')
    m = pat.search(src)
    if not m: continue

    pos = m.end()
    snips = []
    while pos < len(src):
        while pos < len(src) and src[pos] in ' \t\n\r,': pos += 1
        if pos >= len(src) or src[pos] == ']': break
        if src[pos] == '"':
            end = pos + 1
            while end < len(src):
                if src[end] == '\\': end += 2; continue
                if src[end] == '"': break
                end += 1
            raw = src[pos+1:end]
            decoded = raw.replace('\\\\', chr(0)).replace('\\"', '"').replace('\\n', '\n').replace(chr(0), '\\')
            snips.append(decoded)
            pos = end + 1
        else: pos += 1

    print(f"\n{clean} (target {target}%, {tlen} chars):")
    for i, s in enumerate(snips):
        dc = diff_count(s)
        pct = dc / len(s) * 100 if s else 0
        ok = 'OK' if abs(pct - target) <= 1.5 else f'PCT={pct:.1f}%'
        print(f"  {i+1:2d}. {ok:15s}  len={len(s):3d}  diff={dc:2d} ({pct:.1f}%)")
