#!/usr/bin/env python
"""
This is a "clone" of netselect.
"""
import logging
import timeit
from operator import itemgetter
from httplib import HTTPConnection


logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)

def list_pypi_hosts():
    """
    Will loop through PyPi mirrors [a-z].pypi.python.org, keeping in mind that
    `a.pypi.python.org` correlates to `pypi.python.org`, and is not a simple
    mirror.
    """
    begin = ord('b')
    end = ord('z')

    for letter in range(begin, end+1):
        mirror_hostname = "%s.pypi.python.org" % chr(letter)
        h = HTTPConnection(mirror_hostname)
        h.request('GET', '/', headers={'User-Agent': 'pypiclone/0.1'})
        resp = h.getresponse()
        if resp.status != 200:
            log.debug("%s does not exist; ending search.", mirror_hostname)
            return

        yield mirror_hostname

def fastest_response_time(url):
    # Hit the URL three times in succession to get a general feel for the
    # response time.
    log.debug("Checking response time for %s", url)
    t = timeit.Timer(
        "h.request('GET', '/', headers={'cache-control': 'no-cache', 'User-Agent': 'pypiclone/0.1'}); h.getresponse()",
        "from httplib import HTTPConnection; h = HTTPConnection('%s')" % url)
    response_times = t.repeat(3, 1)
    return min(response_times)

def list_fastest_mirror():
    mirrors_and_times = sorted([
        (mirror_url, fastest_response_time(mirror_url))
        for mirror_url in list_pypi_hosts()], key=itemgetter(1))

    if not mirrors_and_times:
        log.info("ERROR: Could not find any suitable PyPi mirrors.")
        raise Exception("No valid mirrors found.")
    
    return mirrors_and_times[0]

def main(argv):
    mirror_url, mirror_response_time = list_fastest_mirror()
    print mirror_url
    return 0

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