import httpx, re, json
from pathlib import Path
import sys

sys.stdout.reconfigure(encoding='utf-8')

env = {}
for line in Path('E:/workSpace/02-ClassFeedback/.env').read_text(encoding='utf-8').split('\n'):
    if '=' in line and not line.startswith('#'):
        k, v = line.split('=', 1)
        env[k.strip()] = v.strip()

client = httpx.Client(base_url=env['OJ_BASE_URL'], follow_redirects=True, timeout=30)
r = client.post('/login', json={'uname': env['OJ_USERNAME'], 'password': env['OJ_PASSWORD']})
print('Login:', r.status_code)

hw_id = '6a35eadbc2880e90d8609759'

# Get problem list
r = client.get(f'/homework/{hw_id}')
problems = re.findall(r'href=\"/p/([^\"]+)\?tid=' + hw_id + r'\"[^>]*><b>([^<]+)</b>(?:&nbsp;|\s)*([^<]*)</a>', r.text)
print('Problems:')
prob_map = {}
for pid, pid_display, pname in problems:
    pname_clean = pname.strip() if pname.strip() else pid_display
    prob_map[pid] = pname_clean
    print(f'  {pid}: {pname_clean}')

# Get all submissions
print('\n--- Student Submissions ---')
student_data = {}

for page in range(1, 11):
    r2 = client.get(f'/record?tid={hw_id}&page={page}')
    if '没有找到相关记录' in r2.text:
        break

    rows = re.findall(r'<tr[^>]*>(.*?)</tr>', r2.text, re.DOTALL)
    found_any = False
    for row in rows:
        if 'col--status' not in row:
            continue
        found_any = True
        name_match = re.search(r'<a[^>]*href=\"/user/\d+\"[^>]*>([^<]+)</a>', row)
        prob_match = re.search(r'href=\"/p/([^\"]+)\?tid=' + hw_id + r'\"[^>]*>([^<]+)</a>', row)
        status_match = re.search(r'record-status--text\s+(\w+)\">([^<]+)<', row)
        score_match = re.search(r'<span[^>]*>\s*(\d+)\s*</span>', row)
        time_match = re.search(r'(\d{2}-\d{2}\s+\d{2}:\d{2})', row)

        if name_match:
            name = name_match.group(1).strip()
            pid = prob_match.group(1) if prob_match else '?'
            pname = prob_map.get(pid, pid)
            status = status_match.group(2).strip() if status_match else '?'
            score = score_match.group(1) if score_match else '?'
            time_str = time_match.group(1) if time_match else '?'

            if name not in student_data:
                student_data[name] = []
            student_data[name].append({
                'problem': pname,
                'status': status,
                'score': score,
                'time': time_str
            })
    if not found_any:
        break

# Our target students
targets = ['杨林轩', '欧俊宇', '汪子杰', '谢明泓']

with open('E:/workSpace/02-ClassFeedback/oj_csp17_result.txt', 'w', encoding='utf-8') as f:
    for name in targets:
        if name in student_data:
            f.write(f'\n【{name}】({len(student_data[name])}次提交):\n')
            for rec in student_data[name]:
                f.write(f'  {rec["problem"]}: {rec["status"]} (得分: {rec["score"]}, 时间: {rec["time"]})\n')
        else:
            f.write(f'\n【{name}】: 无提交记录\n')

    f.write('\n--- All students found ---\n')
    for name in sorted(student_data.keys()):
        f.write(f'  {name}: {len(student_data[name])} submissions\n')

print('Done! Results written to oj_csp17_result.txt')
