"""Count NPI references per Organization in a CMS National Provider Directory release.

Read uncompressed NDJSON from stdin. Rows belong to one Organization release.
This reports resource references. It does not determine network participation.
"""

import collections
import json
import sys

API_NPI_SYSTEM = "http://hl7.org/fhir/sid/us-npi"
BULK_NPI_SYSTEM = "http://terminology.hl7.org/NamingSystem/npi"
ORG_TYPES = "http://terminology.hl7.org/CodeSystem/organization-type"


def count_organizations(stream):
    rows_by_npi = collections.Counter()
    provider_npis = set()
    group_npis = set()
    resource_ids = set()
    stats = collections.Counter()
    for number, line in enumerate(stream, 1):
        row = json.loads(line)
        if row.get("resourceType") != "Organization" or not row.get("id"):
            raise ValueError(f"Line {number} is missing an Organization resource ID")
        key = row["id"]
        if key in resource_ids:
            raise ValueError(f"Repeated resource ID on line {number}")
        resource_ids.add(key)
        npis = set()
        for identifier in row.get("identifier", []):
            system = identifier.get("system")
            if system not in (API_NPI_SYSTEM, BULK_NPI_SYSTEM):
                continue
            value = identifier.get("value")
            if not (isinstance(value, str) and len(value) == 10 and value.isascii() and value.isdigit()):
                stats["malformed_npi_values"] += 1
                continue
            stats["npi_identifier_values"] += 1
            if system == API_NPI_SYSTEM:
                stats["api_system_identifier_values"] += 1
            else:
                stats["bulk_system_identifier_values"] += 1
            npis.add(value)
        if npis:
            stats["resources_with_npi"] += 1
        if len(npis) > 1:
            stats["resources_with_multiple_npis"] += 1
        rows_by_npi.update(npis)
        types = row.get("type", [])
        is_provider = any(
            code.get("system") == ORG_TYPES and code.get("code") == "prov"
            for kind in types for code in kind.get("coding", [])
        )
        is_group = any(kind.get("text") == "ein" for kind in types)
        if is_provider:
            stats["provider_type_resources"] += 1
            provider_npis.update(npis)
        if is_group:
            stats["ein_type_resources"] += 1
            group_npis.update(npis)
    stats.update({
        "organization_resources": len(resource_ids),
        "distinct_npi_values": len(rows_by_npi),
        "distinct_npi_resource_pairs": sum(rows_by_npi.values()),
        "npis_on_multiple_resources": sum(1 for count in rows_by_npi.values() if count > 1),
        "npis_on_both_provider_and_ein": len(provider_npis & group_npis),
    })
    if not resource_ids:
        raise ValueError("The input contains no Organization resources")
    return {key: stats[key] for key in (
        "organization_resources", "resources_with_npi", "resources_with_multiple_npis",
        "npi_identifier_values", "api_system_identifier_values", "bulk_system_identifier_values",
        "malformed_npi_values", "distinct_npi_resource_pairs",
        "distinct_npi_values", "npis_on_multiple_resources", "provider_type_resources",
        "ein_type_resources", "npis_on_both_provider_and_ein",
    )}


if __name__ == "__main__":
    try:
        result = count_organizations(sys.stdin.buffer)
    except (ValueError, TypeError, AttributeError) as error:
        sys.exit(f"Could not count this release: {error}")
    print(json.dumps(result, indent=2))
