import sys, urllib2, simplejson

def main(args):
    print "Solving problem at " + args[1]
    # The first program argument should be the URL of the configuration that we wish to make
    #   i.e. http://santa.kirit.com/program/17959aa371fd744b858cc10bdb6ad0662634a19f/new/1/
    request = urllib2.urlopen(args[1], 'null')
    # Assuming this is succesful the final URL will be the redirection to the city page. We can
    # then get the initial information by asking for the JSON blob.
    status = simplejson.JSONDecoder().decode(urllib2.urlopen(request.url + 'json/').read())
    # The 'completed' time stamp will be filled in when the final city is visited
    while not status['problem']['completed']:
        next = None
        # The revealed list shows us cities we've been told about. The city ordering is stable,
        # but newly revealed cities may appear anywhere in the list
        for city in status['revealed']:
            # Find the first city we've not visited
            if not city['visited']:
                print city
                for k in city.keys():
                    # Find the first key which is not 'visited' and then use that as the direction to move in
                    if k != 'visited':
                        next = simplejson.JSONDecoder().decode(urllib2.urlopen(request.url + ('json/%s/' % k), 'null').read())
                        break
                break
        # Make sure we've refreshed the status properly
        if next:
            status = next
        else:
            status = simplejson.JSONDecoder().decode(urllib2.urlopen(request.url + 'json/').read())

if __name__ == "__main__":
    sys.exit(main(sys.argv))
