#!/usr/bin/python

import os.path
import xml.etree.ElementTree as ET

ns = {'index': 'http://www.rfc-editor.org/rfc-index'}
names = {
    'UNKNOWN'               : 'unclassified',
    'INTERNET STANDARD'     : 'standard',
    'EXPERIMENTAL'          : 'experimental',
    'HISTORIC'              : 'historic',
    'INFORMATIONAL'         : 'informational',
    'PROPOSED STANDARD'     : 'proposed-standard',
    'DRAFT STANDARD'        : 'draft-standard',
    'BEST CURRENT PRACTICE' : 'best-current-practice',
}
NOW = 'NOW'
PUB = 'PUB'
OLD = 'OLD'

def getDocId(entry):
  docid = entry.find('./index:doc-id', ns)
  if docid is None:
    raise ValueError, 'Element %s is missing a docid' % (entry, )
  numid = int(docid.text[3:])
  return numid

def getStatus(entry, kind, allow_fail):
  child = '%s-status' % kind
  status = entry.find('./index:%s' % child, ns)
  if status is None:
    if allow_fail:
      return None
    else:
      raise ValueError, 'Element %s is missing a %s child ' % (entry, child)
  else:
    return names[status.text]

def getNowStatus(entry):
  return getStatus(entry, 'current', False)

def getPubStatus(entry):
  return getStatus(entry, 'publication', True)

def isObsolete(entry):
  obsoleted_by = entry.find('./index:obsoleted-by', ns)
  return obsoleted_by is not None

print "Loading the rfc index..."

index = ET.parse('../extra/rfc-index.xml')
status = {}
notissued = set()
fyi = set()
maxrfc = -1
minrfc = 1000

print "Parsing entries..."

for entry in index.findall('./index:rfc-entry', ns):
  rfc_id = getDocId(entry)
  status[rfc_id] = {
    NOW: getNowStatus(entry),
    PUB: getPubStatus(entry),
    OLD: isObsolete(entry),
  }
  maxrfc = max(maxrfc, rfc_id)
  minrfc = min(minrfc, rfc_id)

for entry in index.findall('./index:rfc-not-issued-entry', ns):
  notissued.add(getDocId(entry))

for entry in index.findall('./index:fyi-entry/index:is-also', ns):
  fyi.add(getDocId(entry))

print "RFC range is %s - %s" % (minrfc, maxrfc)

len1 = 0
for p in names.values():
  len1 = max(len1, 4 + len(p))

with open('rfc-status.txt', 'w') as out:
  for rfc in range(minrfc, maxrfc+1):
    if rfc in notissued:
      continue
    have = os.path.exists('../rfc-%s.txt' % rfc)
    if rfc not in status and not have:
      continue
    now = status[rfc][NOW]
    category = ('for-your-information' if rfc in fyi else
      ('old/%s' % now if status[rfc][OLD] else now))
    print >> out, "%04d %-*s" % (rfc, len1, category)

print "done."
