#!/usr/bin/env python3
"""Create a deterministic LinkedIn Lead Gen population receipt from normalized JSON."""
from collections import Counter
from hashlib import sha256
import json
from pathlib import Path
import sys


def identity(row):
    return row["submission_scope"], row["submission_id"]


def audit(population):
    if population.get("source_completeness") != "COMPLETE":
        unknown_states = {state: "UNKNOWN" for state in ("YES", "NO", "UNKNOWN")}
        return {
            "submitted_unique": "UNKNOWN",
            "delivery_attempts": "UNKNOWN",
            "received_unique": "UNKNOWN",
            "accepted_unique": "UNKNOWN",
            "contacted": dict(unknown_states),
            "qualified": dict(unknown_states),
            "booked": dict(unknown_states),
            "held": dict(unknown_states),
            "qualified_resolved_rate": {
                "numerator": "UNKNOWN",
                "denominator": "UNKNOWN",
                "value": "UNDEFINED",
                "unknown_among_accepted": "UNKNOWN",
            },
        }
    records = population["records"]
    attempts = population["delivery_attempts"]
    events = population["events"]
    production = {
        identity(row): row
        for row in records
        if row["test_flag"] is False
        and population["cohort_start"] <= row["submitted_at"] <= population["cohort_end"]
    }
    received = {key: row for key, row in production.items() if row["received_state"] == "YES"}
    accepted = {key: row for key, row in production.items() if row["accepted_state"] == "YES"}
    event_map = {
        (identity(event), event["event_type"]): event
        for event in events
        if event["event_type"] in {"CONTACTED", "QUALIFIED", "BOOKED", "HELD"}
        and event["event_at"] != "Unknown"
        and event["event_at"] <= population["cutoff"]
    }
    result = {
        "submitted_unique": len(production),
        "delivery_attempts": len({
            row["transport_attempt_id"]
            for row in attempts
            if identity(row) in production
            and row["attempted_at"] <= population["cutoff"]
        }),
        "received_unique": len(received),
        "accepted_unique": len(accepted),
    }
    for dimension in ("contacted", "qualified", "booked", "held"):
        counts = Counter(
            event_map[(key, dimension.upper())]["state"]
            if (key, dimension.upper()) in event_map else "UNKNOWN"
            for key in accepted
        )
        result[dimension] = {state: counts[state] for state in ("YES", "NO", "UNKNOWN")}
    qualified = result["qualified"]
    denominator = qualified["YES"] + qualified["NO"]
    result["qualified_resolved_rate"] = {
        "numerator": qualified["YES"],
        "denominator": denominator,
        "value": "UNDEFINED" if denominator == 0 else qualified["YES"] / denominator,
        "unknown_among_accepted": qualified["UNKNOWN"],
    }
    return result


def main():
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python3 audit-linkedin-lead-gen-population.py normalized.json")
    source = Path(sys.argv[1])
    raw = source.read_bytes()
    document = json.loads(raw)
    population = document.get("measurement_fixture", document)
    receipt = {
        "tool": "audit-linkedin-lead-gen-population.py",
        "input_sha256": sha256(raw).hexdigest(),
        "result": audit(population),
    }
    print(json.dumps(receipt, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()
