"""Educational paired FASTQ quality audit. Phred+33; four-line records."""
import argparse
import csv
import gzip
from itertools import zip_longest
from pathlib import Path


def records(path):
    opener = gzip.open if str(path).endswith(".gz") else open
    with opener(path, "rt", encoding="ascii") as f:
        while True:
            h = f.readline()
            if not h:
                return
            seq, plus, qual = [f.readline().rstrip("\r\n") for _ in range(3)]
            if not h.startswith("@") or not h[1:].strip() or not plus.startswith("+") or not seq or len(seq) != len(qual):
                raise ValueError("Malformed FASTQ: " + str(path))
            if not set(seq.upper()) <= set("ACGTN") or any(not 33 <= ord(q) <= 126 for q in qual):
                raise ValueError("Invalid bases or quality: " + str(path))
            name = h[1:].split()[0]
            if name.endswith(("/1", "/2")):
                name = name[:-2]
            yield name, [ord(q)-33 for q in qual]


def audit(r1, r2):
    stats = [{}, {}]
    pairs = 0
    for a, b in zip_longest(records(r1), records(r2)):
        if a is None or b is None or a[0] != b[0]:
            raise ValueError("Unequal counts or mismatched read IDs")
        pairs += 1
        for mate, (_, scores) in enumerate((a, b)):
            for i, q in enumerate(scores, 1):
                cell = stats[mate].setdefault(i, [0, 0, 0])
                cell[0] += 1
                cell[1] += q
                cell[2] += q >= 30
    if not pairs:
        raise ValueError("No read pairs")
    return pairs, stats


def demo(out):
    paths = [out / "demo_R1.fastq", out / "demo_R2.fastq"]
    for mate, path in enumerate(paths, 1):
        with path.open("w", encoding="ascii") as f:
            for i in range(1, 5):
                q = [35]*40 if mate == 1 else [35]*30+[20]*10
                f.write(f"@synthetic_{i}/{mate}\n" + "ACGT"*10 + "\n+\n" + "".join(chr(x+33) for x in q) + "\n")
    return paths


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--demo", action="store_true")
    p.add_argument("--r1", type=Path)
    p.add_argument("--r2", type=Path)
    p.add_argument("--out", type=Path, required=True)
    a = p.parse_args()
    if (a.demo and (a.r1 or a.r2)) or (not a.demo and not (a.r1 and a.r2)):
        p.error("Use --demo or both --r1 and --r2")
    a.out.mkdir(parents=True, exist_ok=True)
    pairs, stats = audit(*(demo(a.out) if a.demo else [a.r1, a.r2]))
    if a.demo:
        assert pairs == 4
        assert stats[1][40] == [4, 80, 0]
        assert sum(v[2] for v in stats[0].values()) == 160
        assert sum(v[2] for v in stats[1].values()) == 120
        print("PASS: four synthetic-data checks")
    with (a.out / "summary.csv").open("w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["mate", "reads", "bases", "mean_phred", "q30_pct"])
        for mate, cycles in enumerate(stats, 1):
            n, total, q30 = map(sum, zip(*cycles.values()))
            w.writerow([mate, pairs, n, f"{total/n:.2f}", f"{100*q30/n:.2f}"])
    with (a.out / "per_cycle.csv").open("w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["mate", "cycle", "bases", "mean_phred", "q30_pct"])
        for mate, cycles in enumerate(stats, 1):
            for i, (n, total, q30) in sorted(cycles.items()):
                w.writerow([mate, i, n, f"{total/n:.2f}", f"{100*q30/n:.2f}"])
    print(f"PASS: {pairs} synchronized read pairs; summaries written to {a.out}")


if __name__ == "__main__":
    main()
