import os
import re

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

COURSE_TYPE_MAP = {
    'AICODE03': 'AICODE03（AICODE03平台）',
    'SPIKE': 'SPIKE（PRIME套装）',
    'DISC': 'DISC（螺丝刀套装45002）',
    'CREATE': 'CREATE（WEDO）',
    'MECH': 'MECH（9686动力机械）',
    'TUBE': 'TUBE（管道游戏套装）',
    'INVENT': 'INVENT（智能笔套装）',
    'WEDO': 'CREATE（WEDO）',
}

def extract_file_info(file_path):
    filename = os.path.basename(file_path)
    parts = os.path.normpath(file_path).split(os.sep)
    
    class_name = None
    student_name = None
    for i, part in enumerate(parts):
        if part == 'feedback':
            if i >= 2:
                student_name = parts[i-1]
                class_name = parts[i-2]
            break
    
    date_match = re.match(r'(\d{4})(\d{2})(\d{2})_', filename)
    date_str = ''
    if date_match:
        date_str = f'{date_match.group(1)}-{date_match.group(2)}-{date_match.group(3)}'
    
    course_match = re.search(r'(AICODE03|SPIKE|DISC|CREATE|MECH|TUBE|INVENT|WEDO)-(\d+)', filename)
    course_code = ''
    if course_match:
        prefix = course_match.group(1)
        if prefix == 'WEDO':
            prefix = 'CREATE'
        num = course_match.group(2).zfill(3)
        course_code = f'{prefix}-{num}'
    
    course_type = ''
    for prefix in ['AICODE03', 'SPIKE', 'DISC', 'CREATE', 'MECH', 'TUBE', 'INVENT']:
        if course_code.startswith(prefix):
            course_type = COURSE_TYPE_MAP.get(prefix, prefix)
            break
    
    return {
        'class_name': class_name or '',
        'student_name': student_name or '',
        'date': date_str,
        'course_code': course_code,
        'course_type': course_type,
        'filename': filename,
    }

def parse_feedback_content(text, file_info):
    result = {
        'theme': '',
        'content': '',
        'assessments': [],
        'highlights': '',
        'concerns': '',
        'confirmed': '',
        'core_performance': '',
    }
    
    lines = text.split('\n')
    content_lines = []
    in_content = False
    in_assessment = False
    in_teacher_notes = False
    in_theme = False
    
    i = 0
    while i < len(lines):
        line = lines[i]
        stripped = line.strip()
        
        if re.match(r'^#\s+\d{4}-\d{2}-\d{2}\s*\|\s*', stripped):
            parts = re.split(r'\s*\|\s*', stripped)
            if len(parts) >= 3:
                result['theme'] = parts[2].strip()
            elif len(parts) >= 2:
                result['theme'] = parts[1].strip()
            i += 1
            continue
        
        if re.match(r'^#\s+课程主题[：:]', stripped):
            result['theme'] = stripped.split('：', 1)[-1].strip() if '：' in stripped else stripped.split(':', 1)[-1].strip()
            i += 1
            continue
        
        theme_match = re.match(r'^\*\*课程主题\*\*[：:]?\s*(.*)', stripped)
        if theme_match:
            result['theme'] = theme_match.group(1).strip()
            i += 1
            continue
        
        core_match = re.match(r'^\*\*核心表现\*\*[：:]?\s*(.*)', stripped)
        if core_match:
            result['core_performance'] = core_match.group(1).strip()
            i += 1
            continue
        
        if re.match(r'^##\s*课评内容', stripped):
            in_content = True
            i += 1
            continue
        
        if re.match(r'^\*\*课评内容\*\*', stripped):
            in_content = True
            i += 1
            continue
        
        if re.match(r'^\*\*能力评估\*\*', stripped):
            in_content = False
            in_assessment = True
            i += 1
            continue
        
        if re.match(r'^\*\*教师备注\*\*', stripped):
            in_content = False
            in_assessment = False
            in_teacher_notes = True
            i += 1
            continue
        
        if re.match(r'^-{3,}\s*$', stripped) and not in_content:
            in_teacher_notes = False
            i += 1
            continue
        
        if in_assessment:
            assess_match = re.match(r'^-\s*(.+?)[：:]\s*(.+)', stripped)
            if assess_match:
                result['assessments'].append(f"- {assess_match.group(1).strip()}：{assess_match.group(2).strip()}")
            i += 1
            continue
        
        if in_teacher_notes:
            note_match = re.match(r'^-\s*亮点[：:]\s*(.*)', stripped)
            if note_match:
                result['highlights'] = note_match.group(1).strip()
                i += 1
                continue
            
            note_match = re.match(r'^-\s*需关注[：:]\s*(.*)', stripped)
            if note_match:
                result['concerns'] = note_match.group(1).strip()
                i += 1
                continue
            
            note_match = re.match(r'^-\s*与档案对应[：:]\s*(.*)', stripped)
            if note_match:
                if not result['highlights']:
                    result['highlights'] = note_match.group(1).strip()
                i += 1
                continue
            
            note_match = re.match(r'^-\s*确认状态[：:]\s*(.*)', stripped)
            if note_match:
                result['confirmed'] = note_match.group(1).strip()
                i += 1
                continue
            
            note_match = re.match(r'^-\s*(.+?)[：:]\s*(.*)', stripped)
            if note_match:
                key = note_match.group(1).strip()
                val = note_match.group(2).strip()
                if '亮点' in key or 'highlight' in key.lower():
                    result['highlights'] = val
                elif '关注' in key or 'concern' in key.lower():
                    result['concerns'] = val
                elif '确认' in key or 'confirm' in key.lower():
                    result['confirmed'] = val
            i += 1
            continue
        
        if in_content:
            if re.match(r'^-{3,}\s*$', stripped):
                in_content = False
                i += 1
                continue
            if re.match(r'^\*\*.*\*\*', stripped):
                in_content = False
                i += 1
                continue
            if re.match(r'^#', stripped):
                in_content = False
                i += 1
                continue
            if re.match(r'^\*学生[：:].*', stripped):
                in_content = False
                i += 1
                continue
            if re.match(r'^\*生成日期[：:].*', stripped):
                in_content = False
                i += 1
                continue
            if re.match(r'^\*记录开始日期[：:].*', stripped):
                in_content = False
                i += 1
                continue
            content_lines.append(line)
            i += 1
            continue
        
        if not in_content and not in_assessment and not in_teacher_notes:
            if stripped and not re.match(r'^(#|---|\*\*.*\*\*|\*.*\*|$)', stripped):
                if not re.match(r'^\*\*(日期|授课日期)\*\*', stripped):
                    if not re.match(r'^#\s+\d{4}-\d{2}-\d{2}', stripped):
                        content_lines.append(line)
        
        i += 1
    
    result['content'] = '\n'.join(content_lines).strip()
    
    if not result['confirmed'] and file_info['date']:
        result['confirmed'] = f'☑ 已确认（{file_info["date"]}）'
    
    return result

def format_feedback(file_info, parsed):
    course_prefix = file_info['course_code'].split('-')[0] if file_info['course_code'] else ''
    
    lines = []
    lines.append(f'# {file_info["course_code"]} 课评')
    lines.append('')
    lines.append(f'**日期**: {file_info["date"]}')
    
    if parsed['theme']:
        lines.append(f'**课程主题**：{parsed["theme"]}')
    
    if parsed['core_performance']:
        lines.append(f'**核心表现**：{parsed["core_performance"]}')
    
    lines.append('')
    lines.append('**课评内容**：')
    lines.append('')
    
    if parsed['content']:
        lines.append(parsed['content'])
    
    if parsed['assessments']:
        lines.append('')
        lines.append('**能力评估**：')
        for a in parsed['assessments']:
            lines.append(a)
    
    lines.append('')
    lines.append('**教师备注**：')
    lines.append(f'- 亮点：{parsed["highlights"]}')
    lines.append(f'- 需关注：{parsed["concerns"]}')
    lines.append(f'- 确认状态：{parsed["confirmed"]}')
    
    lines.append('')
    lines.append('---')
    lines.append('')
    lines.append('---')
    
    student_display = file_info['student_name']
    lines.append(f'*学生：{student_display} | 课程：{file_info["course_type"]}*')
    lines.append('*记录开始日期：2026-03-25*')
    
    return '\n'.join(lines)

def is_already_target_format(text, file_info):
    lines = text.strip().split('\n')
    if not lines:
        return False
    
    first_line = lines[0].strip()
    expected_title = f'# {file_info["course_code"]} 课评'
    if first_line != expected_title:
        return False
    
    has_date = False
    has_content = False
    has_teacher_notes = False
    has_footer = False
    
    for line in lines:
        stripped = line.strip()
        if re.match(r'^\*\*日期\*\*', stripped):
            has_date = True
        if re.match(r'^\*\*课评内容\*\*', stripped):
            has_content = True
        if re.match(r'^\*\*教师备注\*\*', stripped):
            has_teacher_notes = True
        if re.match(r'^\*学生[：:].*\|.*课程[：:]', stripped):
            has_footer = True
    
    return has_date and has_content and has_teacher_notes and has_footer

def process_feedback_file(file_path):
    file_info = extract_file_info(file_path)
    
    with open(file_path, 'r', encoding='utf-8') as f:
        text = f.read()
    
    if is_already_target_format(text, file_info):
        return False
    
    parsed = parse_feedback_content(text, file_info)
    new_text = format_feedback(file_info, parsed)
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(new_text)
    
    return True

def main():
    updated_count = 0
    skipped_count = 0
    error_count = 0
    
    for root, dirs, files in os.walk(CLASS_DIR):
        if 'feedback' 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 process_feedback_file(file_path):
                    updated_count += 1
                    print(f'  ✅ 已更新: {os.path.relpath(file_path, CLASS_DIR)}')
                else:
                    skipped_count += 1
            except Exception as e:
                error_count += 1
                print(f'  ❌ 错误: {os.path.relpath(file_path, CLASS_DIR)} - {e}')
    
    print(f'\n{"="*50}')
    print(f'更新完成！')
    print(f'  ✅ 已更新: {updated_count} 个文件')
    print(f'  ⏭️  已跳过(已是最新格式): {skipped_count} 个文件')
    print(f'  ❌ 错误: {error_count} 个文件')

if __name__ == '__main__':
    main()