"""Compare facility NPI and plan segment pairs in Peak Health's public CY2027 files.

Run locally: python3 compare-peak-plans.py mpf.json org-includes.json plans.json
The second file is a complete OrganizationAffiliation search with organizations
included. The third is a complete InsurancePlan search. No network calls.
"""
import argparse
from collections import defaultdict
from datetime import date
import hashlib
import json
from pathlib import Path
import re
import sys


YEAR = "2027"
CONTRACT = "H8947"
NPI_SYSTEMS = {"http://hl7.org/fhir/sid/us-npi", "http://terminology.hl7.org/NamingSystem/npi"}
PLAN_SYSTEM = "http://cms.gov/medicare/ma-plan-id"


def require(condition, message):
    if not condition:
        raise ValueError(message)


def load_source(path):
    raw = path.read_bytes()
    return json.loads(raw), {"bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest()}


def search_results(bundle, match_type, included_type=None):
    require(bundle.get("resourceType") == "Bundle" and bundle.get("type") == "searchset",
            "Expected a FHIR searchset Bundle")
    require(not any(link.get("relation") in {"next", "previous"} for link in bundle.get("link", [])),
            "Paged Bundle: provide the complete search")
    matches, included = {}, {}
    for entry in bundle.get("entry", []):
        row = entry["resource"]
        kind = row["resourceType"]
        if kind == match_type and entry["search"]["mode"] == "match":
            target = matches
        elif kind == included_type and entry["search"]["mode"] == "include":
            target = included
        else:
            raise ValueError("Unexpected resource or search mode: " + kind)
        key = kind + "/" + row["id"]
        require(key not in target, "Duplicate FHIR resource: " + key)
        target[key] = row
    require(len(matches) == bundle.get("total"), "Bundle is missing matching resources")
    return matches.values(), included


def identifiers(resource, systems):
    return {item["value"] for item in resource.get("identifier", []) if item.get("system") in systems}


def full_year(period):
    # Partial-year relationships need dated observations on both surfaces.
    start = date.fromisoformat(period["start"]) if "start" in period else date.min
    end = date.fromisoformat(period["end"]) if "end" in period else date.max
    return start <= date(int(YEAR), 1, 1) and end >= date(int(YEAR), 12, 31)


def npi(value):
    require(isinstance(value, str) and re.fullmatch("[0-9]{10}", value), "Expected a ten-digit NPI")
    return value


def plan_segment(value):
    require(isinstance(value, str) and re.fullmatch(CONTRACT + "-[0-9]{3}-[0-9]{3}", value),
            "Expected an H8947 contract-plan-segment identifier")
    return value


def fhir_pairs(affiliations, plans):
    plan_rows, _ = search_results(plans, "InsurancePlan")
    plans_by_network = defaultdict(set)
    for row in plan_rows:
        require(row.get("status") in {"active", "retired"}, "Unexpected InsurancePlan status")
        if row["status"] == "retired":
            continue
        period = row["period"]
        require("start" in period and "end" in period and full_year(period),
                "Plan is not explicitly dated for all of CY2027")
        ids = identifiers(row, {PLAN_SYSTEM})
        require(len(ids) == 1 and row.get("network"), "Missing plan identifier or network")
        require(not row.get("plan"), "Nested plan benefits or networks need a separate mapping")
        segment = plan_segment(ids.pop())
        for network in row["network"]:
            plans_by_network[network["reference"]].add(segment)

    aff_rows, organizations = search_results(affiliations, "OrganizationAffiliation", "Organization")
    pairs, facilities = set(), set()
    for link in aff_rows:
        require(isinstance(link.get("active"), bool), "Unspecified affiliation activity")
        if not link["active"]:
            continue
        require(full_year(link.get("period", {})), "Partial-year affiliation needs separate review")
        ref = link["organization"]["reference"]
        require(ref in organizations and not link.get("participatingOrganization"),
                "Missing included facility or a different affiliation layout")
        org = organizations[ref]
        require(org.get("active") is True, "An active affiliation points to an unconfirmed facility")
        codes = {(c.get("system"), c.get("code")) for t in org.get("type", []) for c in t.get("coding", [])}
        require(("http://hl7.org/fhir/us/davinci-pdex-plan-net/CodeSystem/OrgTypeCS", "fac") in codes,
                "The included organization is not labeled as a facility")
        values = identifiers(org, NPI_SYSTEMS)
        require(len(values) == 1, "Expected one identified NPI per included facility")
        facility = npi(values.pop())
        facilities.add(facility)
        require(link.get("network"), "Missing facility network")
        for network in link["network"]:
            ref = network["reference"]
            require(ref in plans_by_network, "Facility refers to an unmatched plan network: " + ref)
            pairs.update((facility, segment) for segment in plans_by_network[ref])
    segments = {s for values in plans_by_network.values() for s in values}
    require(segments and facilities, "No eligible plans or facilities found")
    return pairs, len(facilities), len(segments), len(plans_by_network)


def plan_finder_pairs(records):
    require(isinstance(records, list), "Expected a Plan Finder JSON array")
    pairs, facilities = set(), set()
    for record in records:
        kind = record.get("type")
        require(kind in {"Individual", "Facility"}, "Unrecognized Plan Finder record type")
        if kind == "Individual":
            continue
        facility = npi(record["npi"])
        for plan in record["plans"]:
            require(isinstance(plan["year"], list) and plan["year"]
                    and all(isinstance(y, str) and re.fullmatch("[0-9]{4}", y) for y in plan["year"]),
                    "Unexpected Plan Finder year format")
            if YEAR in plan["year"]:
                facilities.add(facility)
                pairs.add((facility, plan_segment(plan["maPlanId"])))
    require(facilities, "No CY2027 facility plan records found")
    return pairs, len(facilities)


def differences(pairs):
    result = defaultdict(list)
    for provider, segment in sorted(pairs):
        result[provider].append(segment)
    return dict(result)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for source in ("mpf", "affiliations", "plans"):
        parser.add_argument(source, type=Path)
    paths = vars(parser.parse_args())
    inputs = {key: load_source(path) for key, path in paths.items()}
    fhir, fhir_count, segments, networks = fhir_pairs(inputs["affiliations"][0], inputs["plans"][0])
    mpf, mpf_count = plan_finder_pairs(inputs["mpf"][0])
    report = {
        "contract": CONTRACT, "plan_year": int(YEAR),
        "input_fingerprints": {key: fingerprint for key, (_, fingerprint) in inputs.items()},
        "fhir_unique_facility_npis": fhir_count, "mpf_unique_facility_npis": mpf_count,
        "fhir_distinct_plan_segments": segments, "fhir_network_references_in_plans": networks,
        "fhir_facility_plan_pairs": len(fhir), "mpf_facility_plan_pairs": len(mpf),
        "shared_pairs": len(fhir & mpf),
        "fhir_only_by_facility": differences(fhir - mpf),
        "mpf_only_by_facility": differences(mpf - fhir),
    }
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
        print(f"Cannot compare these inputs: {exc}", file=sys.stderr)
        sys.exit(2)
