import re, os

outdir = os.path.join(os.path.dirname(__file__), 'chapters')
counts = {'labels': 0, 'dashes': 0, 'rules': 0, 'chapnum': 0, 'secnum': 0, 'emdashtext': 0}

for fname in sorted(os.listdir(outdir)):
    if not fname.endswith('.tex') or fname == 'ch13-conclusion.tex':
        continue

    fpath = os.path.join(outdir, fname)
    with open(fpath, 'r', encoding='utf-8') as f:
        content = f.read()

    # 1. Remove Unicode labels like \label{ux7b2c...}
    label_pattern = re.compile(r'\\label\{[^}]*ux[0-9a-f]+[^}]*\}')
    matches = label_pattern.findall(content)
    counts['labels'] += len(matches)
    content = label_pattern.sub('', content)

    # 2. Fix dashes + strip chapter number prefix (first line)
    lines = content.split('\n')
    if lines and lines[0].startswith('\\chapter{'):
        old_line = lines[0]
        new_line = old_line.replace('------', '——')
        new_line = re.sub(r'\\chapter\{第\d+章[：:\s]+', r'\\chapter{', new_line)
        if new_line != old_line:
            if '------' in old_line:
                counts['dashes'] += 1
            if re.search(r'第\d+章', old_line):
                counts['chapnum'] += 1
        lines[0] = new_line
    content = '\n'.join(lines)

    # 3. Remove decorative rules
    rule = '\\begin{center}\\rule{0.5\\linewidth}{0.5pt}\\end{center}'
    count = content.count(rule)
    counts['rules'] += count
    content = content.replace(rule + '\n\n', '\n')
    content = content.replace(rule + '\n', '\n')

    # 4. Fix em-dashes in body text
    count = content.count('------')
    counts['emdashtext'] += count
    content = content.replace('------', '——')

    # 5. Strip numeric prefixes from section/subsection/subsubsection
    for cmd in ['section', 'subsection', 'subsubsection']:
        def make_stripper(cmd_name):
            def strip_num(m):
                title = m.group(1)
                new_title = re.sub(r'^\d+\.(\d+(\.\d+)?)?\s*', '', title)
                if new_title != title:
                    counts['secnum'] += 1
                    return '\\' + cmd_name + '{' + new_title + '}'
                return m.group(0)
            return strip_num
        pattern = re.compile(r'\\' + cmd + r'\{([^}]+)\}')
        content = pattern.sub(make_stripper(cmd), content)

    with open(fpath, 'w', encoding='utf-8') as f:
        f.write(content)

    print(f'OK {fname}')

print(f'Done: labels={counts["labels"]} dashes={counts["dashes"]} rules={counts["rules"]} chapnum={counts["chapnum"]} secnum={counts["secnum"]} emdash_text={counts["emdashtext"]}')
