from typing import Iterator
from typing import Dict
from typing import Tuple
from typing import Optional
import logging


def _parse_as_to_org_map_remainder(
    f: Iterator[str], org_id_to_country_map: Dict[str, Tuple[str, str]]
) -> Dict[int, Tuple[str, Optional[str], Optional[str]]]:
  # pyformat: disable
  """Returns a mapping of ASNs to organization info from a file.

  Args:
    f: an iterator containing the content of an as-org2info.txt file which
      has already been iterated over by _parse_org_name_to_country_map so the
      only remaining line are of the format
        LVLT-ARIN|20120130|Level 3 Communications, Inc.|US|ARIN
    org_id_to_country_map: Dict {as_name -> ("readable name", country_code)}

  Returns:
    Dict {asn -> (asn_name, readable_name, country)}
    ex {204867 : ("LIGHTNING-WIRE-LABS", "Lightning Wire Labs GmbH", "DE")}
    The final 2 fields may be None
  """
  # pyformat: enable
  asn_to_org_info_map: Dict[int, Tuple[str, Optional[str], Optional[str]]] = {}

  for line in f:
    asn, changed_date, asn_name, org_id, opaque_id, source = line.split("|")
    try:
      readable_name, country = org_id_to_country_map[org_id]
      asn_to_org_info_map[int(asn)] = (asn_name, readable_name, country)
    except KeyError as e:
      logging.warning("Missing org country info for asn %s, %s", asn, e)
      asn_to_org_info_map[int(asn)] = (asn_name, None, None)

  return asn_to_org_info_map