import sys
import xml.etree.ElementTree as ET
from xml.dom import minidom

def get_time_minutes(time_str):
    h, m = map(int, time_str.split(':'))
    return h * 60 + m

def generate_feed():
    # Read config
    with open('../dq2026/judge/config.txt', 'r') as f:
        config_lines = [l.strip() for l in f.readlines()]
    
    title = config_lines[0]
    
    # Read problems
    problems = []
    # Find empty line
    idx = 0
    while config_lines[idx] != "":
        idx += 1
    idx += 1
    
    prob_labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for i in range(idx, len(config_lines)):
        if not config_lines[i]:
            continue
        parts = config_lines[i].split(';')
        name = parts[0].strip()
        label = prob_labels[i - idx]
        problems.append((label, name))
        
    # Read teams
    teams = []
    with open('../dq2026/judge/teams.txt', 'r') as f:
        for line in f:
            if not line.strip() or 'Duke ACM' in line or '@' in line:
                continue
            parts = line.strip().split(';')
            if len(parts) >= 4:
                tid = parts[0]
                tname = parts[3]
                teams.append((tid, tname))
                
    # Create XML
    root = ET.Element('contest')
    info = ET.SubElement(root, 'info')
    ET.SubElement(info, 'contest-id').text = 'contest1'
    ET.SubElement(info, 'title').text = title
    ET.SubElement(info, 'formal_name').text = title
    ET.SubElement(info, 'length').text = '05:00:00'
    ET.SubElement(info, 'scoreboard-freeze-length').text = '01:00:00'
    
    # Create a group
    grp = ET.SubElement(root, 'group')
    ET.SubElement(grp, 'id').text = '1'
    ET.SubElement(grp, 'name').text = 'Main Group'
    
    org = ET.SubElement(root, 'organization')
    ET.SubElement(org, 'id').text = '1'
    ET.SubElement(org, 'name').text = 'Org'
    ET.SubElement(org, 'formal_name').text = 'Organization'

    prob_map = {}
    prob_idx = 1
    for label, name in problems:
        p = ET.SubElement(root, 'problem')
        ET.SubElement(p, 'id').text = str(prob_idx)
        ET.SubElement(p, 'label').text = label
        ET.SubElement(p, 'name').text = name
        prob_map[label] = str(prob_idx)
        prob_idx += 1
        
    team_map = {}
    team_idx = 1
    for tid, tname in teams:
        team_map[tid] = str(team_idx)
        t = ET.SubElement(root, 'team')
        ET.SubElement(t, 'id').text = str(team_idx)
        ET.SubElement(t, 'name').text = tname
        ET.SubElement(t, 'formal_name').text = tname
        ET.SubElement(t, 'organization_id').text = '1'
        ET.SubElement(t, 'group_id').text = '1'
        team_idx += 1
        
    # Parse runs
    with open('../dq2026/judge/judgements.txt', 'r') as f:
        run_id = 1
        for line in f:
            line = line.strip()
            if not line:
                continue
            # 00:09,ttk10,I,C++,PI_01.cc;A
            if ';' not in line:
                continue
            left, ans = line.split(';')
            ans = ans.strip()
            parts = left.split(',')
            if len(parts) != 5:
                continue
            
            time_str, tid, prob, lang, fname = parts
            minutes = get_time_minutes(time_str)
            
            run = ET.SubElement(root, 'run')
            ET.SubElement(run, 'id').text = str(run_id)
            ET.SubElement(run, 'judged').text = 'True'
            ET.SubElement(run, 'language').text = lang
            ET.SubElement(run, 'penalty').text = 'True'
            ET.SubElement(run, 'problem').text = prob_map.get(prob, '1')
            
            result = 'AC' if ans == 'A' else 'WA'
            ET.SubElement(run, 'result').text = result
            
            solved = 'True' if ans == 'A' else 'False'
            ET.SubElement(run, 'solved').text = solved
            
            ET.SubElement(run, 'team').text = team_map.get(tid, '1')
            ET.SubElement(run, 'time').text = str(minutes)
            
            run_id += 1
            
    xml_str = minidom.parseString(ET.tostring(root)).toprettyxml(indent="  ")
    with open('feed.xml', 'w') as f:
        f.write(xml_str)

if __name__ == '__main__':
    generate_feed()
