"""Educational diversity analysis of synthetic counts; Python standard library only."""
import argparse
import csv
import math
from itertools import combinations
from pathlib import Path


def read_counts(path):
    with open(path, newline="", encoding="utf-8") as f:
        reader = csv.reader(f)
        header = next(reader, [])
        if len(header) < 2 or header[0] != "sample_id" or len(set(header)) != len(header):
            raise ValueError("Expected sample_id and unique taxon columns")
        data = {}
        for row in reader:
            if len(row) != len(header) or not row[0].strip() or row[0] in data:
                raise ValueError("Invalid row or duplicate sample ID")
            values = [int(x) for x in row[1:]]
            if any(x < 0 for x in values):
                raise ValueError("Counts must be nonnegative integers")
            data[row[0]] = values
    if not data:
        raise ValueError("No samples")
    return data


def proportions(counts):
    total = sum(counts)
    return [x / total for x in counts] if total else None


def alpha(counts):
    p = proportions(counts)
    if p is None:
        return None, None, None
    richness = sum(x > 0 for x in p)
    shannon = -sum(x * math.log(x) for x in p if x > 0)
    return richness, shannon, shannon / math.log(richness) if richness > 1 else None


def bray_curtis(a, b):
    p, q = proportions(a), proportions(b)
    if p is None or q is None:
        return None
    return sum(abs(x-y) for x, y in zip(p, q)) / sum(x+y for x, y in zip(p, q))


def self_test():
    r, h, j = alpha([25, 25, 25, 25])
    assert r == 4 and math.isclose(h, math.log(4)) and math.isclose(j, 1)
    assert alpha([100, 0, 0, 0]) == (1, 0, None)
    assert alpha([0, 0, 0, 0]) == (None, None, None)
    assert math.isclose(bray_curtis([1, 1], [2, 2]), 0)
    assert math.isclose(bray_curtis([1, 0], [0, 1]), 1)
    assert math.isclose(bray_curtis([25, 25, 25, 25], [85, 5, 5, 5]), 0.6)
    assert bray_curtis([0, 0], [1, 1]) is None
    print("PASS: 7 diversity checks")


def write_table(path, header, rows):
    with open(path, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(header)
        for row in rows:
            writer.writerow(["NA" if x is None else f"{x:.6f}" if isinstance(x, float) else x for x in row])


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", nargs="?", default="synthetic_counts.csv")
    parser.add_argument("--out", default="results")
    parser.add_argument("--self-test", action="store_true")
    args = parser.parse_args()
    self_test()
    if args.self_test:
        return
    data = read_counts(args.input)
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    write_table(out / "alpha.csv", ["sample_id", "richness", "shannon_ln", "pielou"],
                [(name, *alpha(values)) for name, values in data.items()])
    write_table(out / "bray_curtis.csv", ["sample_a", "sample_b", "bray_curtis_relative_abundance"],
                [(a, b, bray_curtis(data[a], data[b])) for a, b in combinations(data, 2)])
    print(f"Processed {len(data)} synthetic samples; wrote {out / 'alpha.csv'} and {out / 'bray_curtis.csv'}")
    print("NA indicates undefined metric; no hypothesis tests were performed.")


if __name__ == "__main__":
    main()
