import requests
import csv


def fetch_trac(base_url):
    """
    Return a fetcher for a Trac instance

    >>> url, n = fetch_trac("https://debathena.mit.edu/trac")("123")
    >>> url
    u'https://debathena.mit.edu/trac/ticket/123'
    >>> n
    u'debathena-ssl-certificates should include a CRL'
    >>> url, n = fetch_trac("https://scripts.mit.edu/trac")("123")
    >>> url
    u'https://scripts.mit.edu/trac/ticket/123'
    >>> n
    u'scripts-remove works poorly with non-Athena accounts'
    """
    def trac_fetcher(ticket):
        url = '%s/ticket/%s' % (base_url, ticket)
        response = requests.get(url + '?format=csv')
        if response.status_code == 200:
            reader = csv.DictReader(response.text.split('\n'))
            row = next(reader)
            return url, row.get('summary', None)
        else:
            return url, None
    return trac_fetcher