import os
import re

CLASS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.claude', 'memory', 'class')

# Known student names per class (from profile.md files)
CLASS_STUDENTS = {
    '发现世界-周四19点': ['梁昕乔', '钟昀昊', '林瀚丞'],
    '发现世界-周六09点': ['余韫', '杨佳兴', '林嘉铭', '胡翰铭'],
    '发现世界-周六19点': ['赖韵恬'],
    'AICODE03小Q周五1900': ['沙佩琪', '李怡瞳', '黄榆斐', '谢善诺'],
    'AICODE03小Q周六1400': ['黄俊博', '陈昕柔', '李汶浩', '曾乐凯'],
    'SPIKE02-周日1030': ['洪一栩', '王骏诚', '吴浩洋', '吴浩骏', '邓琬颖', '邓琬曦', '方柳莫'],
    'Wedo创造世界-周六1030': ['黄馨宸', '黄晓瑜', '罗钧龄', '简思霖', '梁家铭', '简思瑜'],
    'Wedo创造世界-周六16点': ['马悦然', '冯彦哲'],
    '发现世界-周日下午16点': [],
    '发明世界-周日14点': [],
    '周日9点': [],
}

def load_student_nicknames():
    nicknames = {}
    for root, dirs, files in os.walk(CLASS_DIR):
        for f in files:
            if f == 'profile.md':
                file_path = os.path.join(root, f)
                parts = os.path.normpath(file_path).split(os.sep)
                class_name = ''
                student_name = ''
                for i, p in enumerate(parts):
                    if p == 'profile.md' and i >= 2:
                        student_name = parts[i-1]
                        class_name = parts[i-2]
                        break
                
                with open(file_path, 'r', encoding='utf-8') as pf:
                    text = pf.read()
                    # Try to find nickname
                    nm = re.search(r'\*\*小名/昵称\*\*\s*\|\s*(\S+)', text)
                    if nm:
                        nick = nm.group(1).strip()
                        if student_name not in nicknames:
                            nicknames[student_name] = []
                        nicknames[student_name].append(nick)
                        nicknames[nick] = student_name
    return nicknames

STUDENT_NICKNAMES = {}

def find_student_for_nickname(nick, class_name):
    """Match a truncated/nickname to full student name for a class"""
    students = CLASS_STUDENTS.get(class_name, [])
    
    # Direct match
    if nick in students:
        return nick
    
    # Match by substring (handles truncated names)
    for student in students:
        if nick in student or student.startswith(nick):
            return student
    
    # Match by nickname
    if STUDENT_NICKNAMES:
        for s in students:
            nicks = STUDENT_NICKNAMES.get(s, [])
            for n in nicks:
                if nick in n or n in nick:
                    return s
    
    return nick

def fix_names_in_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        text = f.read()
    
    parts = os.path.normpath(file_path).split(os.sep)
    class_name = ''
    for i, p in enumerate(parts):
        if p == 'summaries' and i >= 1:
            class_name = parts[i-1]
            break
    
    if class_name not in CLASS_STUDENTS:
        return False
    
    students = CLASS_STUDENTS[class_name]
    if not students:
        return False
    
    lines = text.split('\n')
    changed = False
    
    # Track names found in the file
    names_in_table = []
    names_in_sections = []
    
    # First pass: find all nicknames used
    for line in lines:
        stripped = line.strip()
        # Check table rows
        if stripped.startswith('|') and not stripped.startswith('|:') and not stripped.startswith('|---'):
            cells = [c.strip() for c in stripped.split('|') if c.strip()]
            if cells and len(cells) >= 2:
                cell = cells[0]
                # Skip header-like cells
                if cell not in ['学生', '状态', '类型', '档案位置', '操作'] and cell not in ['序号']:
                    names_in_table.append(cell)
        
        # Check section headers
        m = re.match(r'^###\s+(.+?)(?:\s*[-—]|\s*$)', stripped)
        if m:
            name = m.group(1).strip()
            # Remove numbering and emoji
            name = re.sub(r'^\d+[.、]\s*', '', name)
            name = re.sub(r'\s*☑.*', '', name)
            name = re.sub(r'\[.*?\]', '', name)
            name = name.strip()
            if name and len(name) < 10:
                names_in_sections.append(name)
    
    if not names_in_table and not names_in_sections:
        return False
    
    # Build mapping from truncated/nickname to full name
    mapping = {}
    for nick in set(names_in_table + names_in_sections):
        full = find_student_for_nickname(nick, class_name)
        if full != nick:
            mapping[nick] = full
    
    if not mapping:
        return False
    
    # Apply mapping to file
    new_lines = []
    for line in lines:
        stripped = line.strip()
        new_line = line
        
        # Fix table rows
        if stripped.startswith('|') and not stripped.startswith('|:') and not stripped.startswith('|---'):
            for nick, full in mapping.items():
                # Escape special regex characters in nick
                escaped_nick = re.escape(nick)
                if re.search(escaped_nick, new_line):
                    new_line = re.sub(r'(?<!\|)' + escaped_nick + r'(?!\w)', full, new_line)
                    if new_line != line:
                        changed = True
        
        # Fix section headers
        for nick, full in mapping.items():
            m = re.match(r'^(###\s*)' + re.escape(nick) + r'(\s*[-—]|$)', new_line)
            if m:
                new_line = m.group(1) + full + ' - 常规学生 ✅'
                changed = True
                break
        
        new_lines.append(new_line)
    
    if changed:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(new_lines))
        return True
    
    return False

def main():
    global STUDENT_NICKNAMES
    STUDENT_NICKNAMES = load_student_nicknames()
    
    fixed = 0
    errors = 0
    
    for root, dirs, files in os.walk(CLASS_DIR):
        if 'summaries' not in root.split(os.sep):
            continue
        
        for f in files:
            if not f.endswith('.md'):
                continue
            file_path = os.path.join(root, f)
            try:
                if fix_names_in_file(file_path):
                    fixed += 1
                    rel = os.path.relpath(file_path, CLASS_DIR)
                    print(f'  ✅ 已修复: {rel}')
            except Exception as e:
                errors += 1
                rel = os.path.relpath(file_path, CLASS_DIR)
                print(f'  ❌ 错误: {rel} - {e}')
    
    print(f'\n已完成！修复: {fixed} 个, 错误: {errors}')

if __name__ == '__main__':
    main()