#!/usr/bin/env python3
"""Click-through rate arithmetic with no dependencies.

  python3 ctr.py ctr CLICKS IMPRESSIONS     CTR in percent: CLICKS / IMPRESSIONS * 100
  python3 ctr.py range CLICKS IMPRESSIONS   the same CTR with a 95% Wilson score interval
  python3 ctr.py file videos.csv            rows of label,impressions,clicks (UTF-8, comma-separated, header allowed):
                                            one CTR per row, then the pooled CTR and the plain average of the row CTRs

Use clicks and impressions from the same report and the same period. For YouTube, "clicks" means the views
that came from counted thumbnail impressions, not total views. Results are printed to 4 decimal places.
"""
import csv
import re
import sys
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP, getcontext

getcontext().prec = 40
GROUPED = re.compile(r"^[+-]?\d{1,3}(,\d{3})+$")
Z = Decimal("1.959964")  # 95% two-sided normal quantile


def num(text, name):
    t = text.strip()
    if "," in t:
        if not GROUPED.match(t):
            raise ValueError("comma only as a thousands separator, like 1,500: " + repr(text))
        t = t.replace(",", "")
    try:
        v = Decimal(t)
    except InvalidOperation:
        raise ValueError(name + " is not a number: " + repr(text))
    if not v.is_finite() or v != v.to_integral_value():
        raise ValueError(name + " must be a whole number: " + repr(text))
    if v < 0:
        raise ValueError(name + " must not be negative")
    return v


def show(v):
    return format(v.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP), "f")


def ctr(clicks, impressions):
    if impressions <= 0:
        raise ValueError("impressions must be greater than 0")
    return clicks / impressions * 100


def wilson(clicks, impressions):
    if clicks > impressions:
        raise ValueError("clicks cannot be more than impressions for an interval")
    n, p, z2 = impressions, clicks / impressions, Z * Z
    centre = (p + z2 / (2 * n)) / (1 + z2 / n)
    half = Z * (p * (1 - p) / n + z2 / (4 * n * n)).sqrt() / (1 + z2 / n)
    return (centre - half) * 100, (centre + half) * 100


def read_rows(path):
    try:
        with open(path, encoding="utf-8-sig", newline="") as f:
            rows = [r for r in csv.reader(f) if any(c.strip() for c in r)]
    except FileNotFoundError:
        raise ValueError("file not found: " + path)
    except UnicodeDecodeError:
        raise ValueError("file is not UTF-8 text: " + path)
    except OSError:
        raise ValueError("cannot read as a file: " + path)
    if rows and len(rows[0]) == 3 and not any(ch.isdigit() for c in rows[0][1:] for ch in c):
        rows = rows[1:]
    if not rows:
        raise ValueError("no data rows in " + path)
    return rows


def main(argv):
    if len(argv) == 3 and argv[0] in ("ctr", "range"):
        clicks, imps = num(argv[1], "clicks"), num(argv[2], "impressions")
        line = "CTR = %s%%" % show(ctr(clicks, imps))
        if clicks > imps:
            line += " (more clicks than impressions: check that both come from the same report)"
        if argv[0] == "range":
            lo, hi = wilson(clicks, imps)
            line += ", 95%% Wilson interval %s%% to %s%%" % (show(lo), show(hi))
        print(line)
    elif len(argv) == 2 and argv[0] == "file":
        rows = read_rows(argv[1])
        total_i = total_c = Decimal(0)
        rates = []
        for i, r in enumerate(rows, 1):
            if len(r) != 3:
                raise ValueError("row %d needs exactly 3 comma-separated columns: label,impressions,clicks" % i)
            try:
                imps, clicks = num(r[1], "impressions"), num(r[2], "clicks")
                rate = ctr(clicks, imps)
            except ValueError as e:
                raise ValueError("row %d: %s" % (i, e))
            total_i += imps
            total_c += clicks
            rates.append(rate)
            note = " (more clicks than impressions: check that both come from the same report)" if clicks > imps else ""
            print("%s: CTR = %s%%%s" % (r[0].strip(), show(rate), note))
        print("Pooled CTR (all clicks / all impressions) = %s%%" % show(ctr(total_c, total_i)))
        print("Plain average of the row CTRs = %s%%" % show(sum(rates) / len(rates)))
    else:
        print(__doc__.strip().split("\n\n")[0])
        return 2
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except ValueError as e:
        print("error: " + str(e))
        sys.exit(1)
