#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Compare directory students vs attendance - output to file for clarity"""
import json, os

BASE = '.claude/memory/class'

with open('.claude/memory/config/attendance_data.json', 'r', encoding='utf-8') as f:
    att = json.load(f)

lines = []
total_missing = 0

for cls_name in sorted(os.listdir(BASE)):
    cls_path = os.path.join(BASE, cls_name)
    if not os.path.isdir(cls_path) or cls_name in ('summaries', '.backup', '.tmp'):
        continue

    # Get all students from directories
    dir_students = {}
    for item in os.listdir(cls_path):
        item_path = os.path.join(cls_path, item)
        if os.path.isdir(item_path):
            if item == '补课':
                for s in os.listdir(item_path):
                    sp = os.path.join(item_path, s)
                    if os.path.isdir(sp):
                        fb = os.path.join(sp, 'feedback')
                        n = len(os.listdir(fb)) if os.path.isdir(fb) else 0
                        dir_students[s] = ('补课', n)
            elif item not in ('summaries', '.backup', '.tmp', '补课'):
                fb = os.path.join(item_path, 'feedback')
                n = len(os.listdir(fb)) if os.path.isdir(fb) else 0
                dir_students[item] = ('正式', n)

    att_students = att.get(cls_name, {})
    missing = {}

    for s, (stype, nfiles) in sorted(dir_students.items()):
        if s not in att_students and nfiles > 0:
            missing[s] = (stype, nfiles)
            total_missing += 1

    if missing:
        lines.append(f'\n【{cls_name}】')
        for s, (stype, nfiles) in sorted(missing.items()):
            lines.append(f'  {s} ({stype}, {nfiles}个课评文件)')

    # Also check if att has students not in dir
    extra = set(att_students.keys()) - set(dir_students.keys())
    if extra:
        if not missing:
            lines.append(f'\n【{cls_name}】')
        for s in sorted(extra):
            lines.append(f'  {s} (出勤数据中有，但目录中没有该学生 — 可能是已删除的目录)')

lines.append(f'\n=== 总计: {total_missing} 个学生有课评文件但未加载到出勤表 ===')

out = '\n'.join(lines)
with open('.claude/memory/config/attendance_check.txt', 'w', encoding='utf-8') as f:
    f.write(out)

print(out)
