"""Check a FlashPPI single-proteome CSV; no model inference or biological validation."""
import argparse
import csv
import json
import math


def summarize(path):
    pairs = set()
    nodes = set()
    minimum = maximum = None
    with open(path, encoding="utf-8-sig", newline="") as handle:
        reader = csv.reader(handle, strict=True)
        if next(reader, None) != ["query_id", "match_id", "contact_score"]:
            raise ValueError("Expected query_id,match_id,contact_score header in that order")
        for number, row in enumerate(reader, start=1):
            if len(row) != 3:
                raise ValueError(f"Record {number}: expected 3 fields")
            query, match, text_score = row
            if any(not value or value != value.strip() for value in (query, match)):
                raise ValueError(f"Record {number}: empty or padded ID")
            if query == match:
                raise ValueError(f"Record {number}: self-pair")
            score = float(text_score)
            if not math.isfinite(score) or not 0 <= score <= 1:
                raise ValueError(f"Record {number}: score must be finite and in [0, 1]")
            pair = tuple(sorted((query, match)))
            if pair in pairs:
                raise ValueError(f"Record {number}: duplicate undirected pair")
            pairs.add(pair)
            nodes.update((query, match))
            minimum = score if minimum is None else min(minimum, score)
            maximum = score if maximum is None else max(maximum, score)
    return {"edges": len(pairs), "proteins_in_edges": len(nodes),
            "min_contact_score": minimum, "max_contact_score": maximum}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", help="single-proteome predictions CSV")
    args = parser.parse_args()
    try:
        result = summarize(args.input)
    except (OSError, UnicodeError, ValueError, csv.Error) as exc:
        parser.exit(1, f"error: {exc}\n")
    print(json.dumps(result, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
