#!/usr/bin/env python3
"""CPM arithmetic with no dependencies.

  python3 cpm.py cpm SPEND IMPRESSIONS      cost per 1,000: SPEND / IMPRESSIONS * 1000
  python3 cpm.py spend CPM IMPRESSIONS      cost of a buy: CPM * IMPRESSIONS / 1000
  python3 cpm.py impressions SPEND CPM      what a budget buys: SPEND / CPM * 1000
  python3 cpm.py file deals.csv             one line per row of label,spend,impressions (UTF-8, comma-separated, header allowed)

Use one currency and, for a sponsor fee, say whether the divisor is impressions or views.
Results are printed to 4 decimal places, like the Koldflux CPM calculator.
"""
import csv
import re
import sys
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP


GROUPED = re.compile(r"^[+-]?\d{1,3}(,\d{3})+(\.\d+)?$")


def num(text):
    t = text.strip()
    if "," in t:
        if not GROUPED.match(t):
            raise ValueError("comma only as a thousands separator, like 1,500; write decimals with a dot: " + repr(text))
        t = t.replace(",", "")
    try:
        v = Decimal(t)
    except InvalidOperation:
        raise ValueError("not a number: " + repr(text))
    if not v.is_finite():
        raise ValueError("not a number: " + repr(text))
    return v


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


def need_positive(v, name):
    if v <= 0:
        raise ValueError(name + " must be greater than 0")
    return v


def need_nonneg(v, name):
    if v < 0:
        raise ValueError(name + " must not be negative")
    return v


def cpm(spend, impressions):
    return need_nonneg(spend, "spend") / need_positive(impressions, "impressions") * 1000


def main(argv):
    if len(argv) == 2 and argv[0] == "file":
        try:
            with open(argv[1], 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: " + argv[1])
        except UnicodeDecodeError:
            raise ValueError("file is not UTF-8 text: " + argv[1])
        except OSError:
            raise ValueError("cannot read as a file: " + argv[1])
        # row 1 is a header only when its spend and impressions cells hold no digit at all
        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 " + argv[1])
        out = []
        for i, r in enumerate(rows, 1):
            if len(r) != 3:
                raise ValueError("row %d needs exactly 3 comma-separated columns: label,spend,impressions" % i)
            try:
                out.append("%s: %s per 1,000" % (r[0].strip(), show(cpm(num(r[1]), num(r[2])))))
            except ValueError as e:
                raise ValueError("row %d: %s" % (i, e))
        print("\n".join(out))
        return
    if len(argv) == 3 and argv[0] == "cpm":
        print("CPM = %s per 1,000" % show(cpm(num(argv[1]), num(argv[2]))))
    elif len(argv) == 3 and argv[0] == "spend":
        print("spend = %s" % show(need_nonneg(num(argv[1]), "CPM") * need_nonneg(num(argv[2]), "impressions") / 1000))
    elif len(argv) == 3 and argv[0] == "impressions":
        print("impressions = %s" % show(need_nonneg(num(argv[1]), "spend") / need_positive(num(argv[2]), "CPM") * 1000))
    else:
        raise ValueError("usage: cpm.py cpm|spend|impressions A B   or   cpm.py file deals.csv")


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