#!/usr/bin/env python3
"""Reanalyze the reconstructed dog genealogies in Car et al. Dataset S1.

Source: https://doi.org/10.6084/m9.figshare.27323778.v1
Download "Dataset S1 -Pedigree information.xlsx" (file 56892671), then run:

    python3 analyze-frd-genealogy.py SOURCE.xlsx OUTPUT_DIRECTORY

Requires openpyxl 3.1 or newer. Writes two three-population summaries plus totals.
"""

import csv
import hashlib
import sys
from collections import Counter
from functools import lru_cache
from pathlib import Path

from openpyxl import load_workbook

EXPECTED_SHA256 = "289a58b4fee07b518712e654389c5a42441a3f54904374bf144d040b52eb072b"
POPULATIONS = ("Morocco", "Ukraine", "Italy")
PROVENANCE_FIELDS = (
    "population",
    "sampled_dogs",
    "inferred_parent_nodes",
    "sampled_dogs_both_parents_sampled",
    "sampled_dogs_one_parent_inferred",
    "sampled_dogs_both_parents_inferred",
    "sampled_dogs_any_parent_inferred",
    "parent_links_to_sampled_dogs",
    "parent_links_to_inferred_nodes",
)
REACH_FIELDS = (
    "population",
    "sampled_dogs",
    "unordered_sampled_dog_pairs",
    "immediate_parent_or_shared_parent",
    "deeper_only",
    "all_traceable_relationships",
    "no_relationship_traced",
    "deeper_share_of_traceable_pct",
)


def identifier(value):
    if value is None:
        return ""
    value = str(value).strip()
    return "" if value.upper() == "NA" else value


def read_population(sheet):
    iterator = sheet.values
    headers = next(iterator)
    father_key = "FatherID" if "FatherID" in headers else "Father"
    mother_key = "MotherID" if "MotherID" in headers else "Mother"
    required = {"OffspringID", father_key, mother_key, "pedigree_r"}
    if not required.issubset(headers):
        raise ValueError(f"Unexpected columns in {sheet.title}")

    types = {}
    parents = {}
    for values in iterator:
        row = dict(zip(headers, values))
        child = identifier(row["OffspringID"])
        if not child:
            continue
        if child in types:
            raise ValueError(f"Repeated ID in {sheet.title}: {child}")
        kind = row["pedigree_r"]
        if kind not in ("true_individual", "inferred_individual"):
            raise ValueError(f"Unexpected pedigree_r in {sheet.title}: {kind}")
        types[child] = kind
        parents[child] = frozenset(
            parent for parent in (identifier(row[father_key]), identifier(row[mother_key])) if parent
        )

    unresolved = {parent for pair in parents.values() for parent in pair if parent not in types}
    if unresolved:
        raise ValueError(f"Unresolved parent IDs in {sheet.title}: {sorted(unresolved)[:5]}")
    return types, parents


def summarize(sheet):
    types, parents = read_population(sheet)
    sampled = sorted(child for child, kind in types.items() if kind == "true_individual")
    provenance = Counter()
    for child in sampled:
        if len(parents[child]) != 2:
            raise ValueError(f"Expected two distinct parents for sampled dog {sheet.title}: {child}")
        inferred_count = sum(types[parent] == "inferred_individual" for parent in parents[child])
        provenance[("both_sampled", "one_inferred", "both_inferred")[inferred_count]] += 1
        for parent in parents[child]:
            provenance["link_to_" + types[parent]] += 1

    visiting = set()

    @lru_cache(maxsize=None)
    def ancestors(child):
        if child in visiting:
            raise ValueError(f"Pedigree cycle in {sheet.title}: {child}")
        visiting.add(child)
        lineage = set(parents[child])
        for parent in parents[child]:
            lineage.update(ancestors(parent))
        visiting.remove(child)
        return frozenset(lineage)

    reach = Counter()
    for index, first in enumerate(sampled):
        first_ancestors = ancestors(first)
        for second in sampled[index + 1 :]:
            second_ancestors = ancestors(second)
            immediate = (
                first in parents[second]
                or second in parents[first]
                or bool(parents[first] & parents[second])
            )
            traceable = (
                first in second_ancestors
                or second in first_ancestors
                or bool(first_ancestors & second_ancestors)
            )
            if immediate and not traceable:
                raise ValueError(f"Inconsistent ancestry in {sheet.title}: {first}, {second}")
            reach["pairs"] += 1
            if immediate:
                reach["immediate"] += 1
            elif traceable:
                reach["deeper"] += 1
            else:
                reach["untraced"] += 1

    provenance_row = {
        "population": sheet.title,
        "sampled_dogs": len(sampled),
        "inferred_parent_nodes": sum(kind == "inferred_individual" for kind in types.values()),
        "sampled_dogs_both_parents_sampled": provenance["both_sampled"],
        "sampled_dogs_one_parent_inferred": provenance["one_inferred"],
        "sampled_dogs_both_parents_inferred": provenance["both_inferred"],
        "sampled_dogs_any_parent_inferred": provenance["one_inferred"] + provenance["both_inferred"],
        "parent_links_to_sampled_dogs": provenance["link_to_true_individual"],
        "parent_links_to_inferred_nodes": provenance["link_to_inferred_individual"],
    }
    traceable = reach["immediate"] + reach["deeper"]
    reach_row = {
        "population": sheet.title,
        "sampled_dogs": len(sampled),
        "unordered_sampled_dog_pairs": reach["pairs"],
        "immediate_parent_or_shared_parent": reach["immediate"],
        "deeper_only": reach["deeper"],
        "all_traceable_relationships": traceable,
        "no_relationship_traced": reach["untraced"],
        "deeper_share_of_traceable_pct": f"{100 * reach['deeper'] / traceable:.1f}",
    }
    return provenance_row, reach_row


def write_summary(path, fields, rows):
    totals = {field: sum(int(row[field]) for row in rows) for field in fields[1:] if field != "deeper_share_of_traceable_pct"}
    totals["population"] = "Total across three populations"
    if "deeper_share_of_traceable_pct" in fields:
        totals["deeper_share_of_traceable_pct"] = (
            f"{100 * totals['deeper_only'] / totals['all_traceable_relationships']:.1f}"
        )
    with path.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows([*rows, totals])
    return totals


def main():
    if len(sys.argv) != 3:
        raise SystemExit("Usage: analyze-frd-genealogy.py SOURCE.xlsx OUTPUT_DIRECTORY")
    source, output = Path(sys.argv[1]), Path(sys.argv[2])
    digest = hashlib.sha256(source.read_bytes()).hexdigest()
    if digest != EXPECTED_SHA256:
        raise ValueError(f"Source workbook SHA-256 differs from analyzed release: {digest}")
    workbook = load_workbook(source, read_only=True, data_only=True)
    if set(workbook.sheetnames) != set(POPULATIONS):
        raise ValueError(f"Unexpected worksheets: {workbook.sheetnames}")
    result_rows = [summarize(workbook[name]) for name in POPULATIONS]
    output.mkdir(parents=True, exist_ok=True)
    parent_totals = write_summary(
        output / "frd-2025-parent-provenance.csv", PROVENANCE_FIELDS, [pair[0] for pair in result_rows]
    )
    reach_totals = write_summary(
        output / "frd-2025-relationship-reach.csv", REACH_FIELDS, [pair[1] for pair in result_rows]
    )
    print(parent_totals)
    print(reach_totals)


if __name__ == "__main__":
    main()
