#!/usr/bin/env python3
"""Count exact adapter sequences in a bounded prefix of untrimmed FASTQ."""
import argparse
from collections import Counter
import gzip
import hashlib
import json
from pathlib import Path

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("fastq", type=Path, nargs="+")
parser.add_argument("--limit", type=int, default=1_000_000)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
if args.limit < 1:
    parser.error("--limit must be positive")

core = b"AGATCGGAAGAGC"
feng = b"AGATCGGAAGAGCTCGTATGCCGTCTTCTGCTTG"
truseq = b"AGATCGGAAGAGCACACGTCTGAACTCCAGTCAC"
candidates = {
    "Illumina_13bp": core,
    "Feng_readthrough_20bp": feng[:20],
    "Feng_readthrough_25bp": feng[:25],
    "Feng_readthrough_full": feng,
    "TruSeq_readthrough_20bp": truseq[:20],
    "TruSeq_readthrough_25bp": truseq[:25],
    "TruSeq_readthrough_full": truseq,
    "smallRNA_12bp": b"TGGAATTCTCGG",
    "Nextera_12bp": b"CTGTCTCTTATA",
}
results = {
    "method": "First N records of existing seeded 10% raw subset; no new random sampling.",
    "scope": "Before trimming and before chr1 selection; exact full-sequence matches only.",
    "limit_per_file": args.limit,
    "candidates": {key: value.decode() for key, value in candidates.items()},
    "samples": [],
}
for path in args.fastq:
    counts, tails, positions = Counter(), Counter(), Counter()
    digest, examples, scanned = hashlib.sha256(), [], 0
    with gzip.open(path, "rb") as handle:
        for _ in range(args.limit):
            name = handle.readline()
            if not name:
                break
            sequence, plus, quality = (handle.readline() for _ in range(3))
            seq = sequence.rstrip(b"\r\n")
            if (not name.startswith(b"@") or not plus.startswith(b"+")
                    or not seq or len(seq) != len(quality.rstrip(b"\r\n"))):
                raise ValueError(f"Invalid FASTQ record {scanned + 1} in {path}")
            scanned += 1
            digest.update(name + sequence + plus + quality)
            for label, adapter in candidates.items():
                counts[label] += adapter in seq
            position = seq.find(core)
            if position >= 0:
                positions[position + 1] += 1
                tail = seq[position + len(core):]
                if len(tail) >= 8:
                    tails[tail[:8].decode()] += 1
            if feng[:25] in seq and len(examples) < 3:
                examples.append({"name": name.strip().decode(),
                                 "sequence": seq.decode(),
                                 "core_start_1based": position + 1})
    sample = {
        "input": str(path.resolve()), "reads_scanned": scanned,
        "sha256_of_scanned_fastq_records": digest.hexdigest(),
        "exact_match_reads": dict(counts),
        "next_8bp_after_core_top10": tails.most_common(10),
        "core_start_1based_counts": dict(sorted(positions.items())),
        "Feng_25bp_examples": examples,
    }
    results["samples"].append(sample)
    print(path.name, scanned, json.dumps(dict(counts)), flush=True)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(results, indent=2) + "\n")
