import json


def get_url_mapping(api, headers=None):
  """Fetch the mapping of project id to url from luci-config.

  Args:
    headers: Optional authentication headers to pass to luci-config.

  Returns:
    A dictionary mapping project id to its luci-config project spec (among
    which there is a repo_url key).
  """
  url = 'https://luci-config.appspot.com/_ah/api/config/v1/projects'

  fetch_result = api.url.fetch(url, step_name='Get project urls',
      headers=headers,
      step_test_data=lambda: api.raw_io.test_api.output(json.dumps({
             'projects': [
                 {
                     'repo_type': 'GITILES',
                     'id': 'recipe_engine',
                     'repo_url': 'https://repo.repo/recipes-py',
                 },
                 {
                     'repo_type': 'GITILES',
                     'id': 'build',
                     'repo_url': 'https://repo.repo/chromium/build',
                 }
             ],
      })))
  mapping = {}

  for project in json.loads(fetch_result)['projects']:
    project = {str(k): str(v) for k, v in project.items()}
    mapping[project['id']] = project
  return mapping