"""Consistency check for the ChartText article. Python 3, standard library only.

It reads the files that the MQL5 scripts wrote and checks the wrap rules a second time, without MetaTrader:

  wrap    wrap_cases.csv and wrap_lines.csv (WrapExport.mq5, UTF-16)
          1. the lines of a case, joined without whitespace, equal the text without whitespace
          2. no line is wider than the limit or longer than 63 UTF-16 code units
          3. no line starts or ends inside a character: a surrogate pair, a combining mark, a zero width joiner
             sequence, a variation selector, a skin tone modifier, or a flag of two regional indicators
             (written with unicodedata, apart from the rule in TextWrap.mqh)
          4. a line could not have taken the first word of the next line of its paragraph:
             the width and the length of the grown line, which MetaTrader measured, exceed a limit
             A break between two paragraphs, and a line next to an empty line, are not checked.
  counts  wrap_counts.csv (WrapExport.mq5): mean number of lines per text, with and without the 63 cap
  shot    a 24-bit or 32-bit BMP screenshot (ChartTextDemo.mq5) and the SHOT journal lines
          rows:  the rightmost dark pixel of each label row is compared with x + the width that TextGetSize() gave
          types: the width of the dark pixels of each object is compared with the width of the stored text and of
                 the sent text, to see which of the two the chart displays (6 pixels inside the border for a box)
  cost    update_cost.csv (UpdateCost.mq5): the median of the runs of every row

It is a second implementation of the rules of the include files. It uses the widths that MetaTrader measured, so it does
not show that those widths are right for the font on screen. The screenshot comparison is the only step that does.

usage:  python chart_text_crosscheck.py wrap   <wrap_cases.csv> <wrap_lines.csv> [character limit, default 63]
        python chart_text_crosscheck.py counts <wrap_counts.csv>
        python chart_text_crosscheck.py shot   <screenshot.bmp> <journal.txt> <scene>
        python chart_text_crosscheck.py cost   <update_cost.csv>
"""
import csv
import re
import statistics
import struct
import sys
import unicodedata

LABEL_LIMIT = 63
TOLERANCE_PX = 6   # my choice: the ink of a glyph does not end exactly at its advance width
ZWJ = "‍"


def units(text):
    """Length in UTF-16 code units, which is what the terminal counts."""
    return sum(2 if ord(c) > 0xFFFF else 1 for c in text)


def read_table(path, columns, delimiter="\t", encoding="cp1252"):
    """Rows as dictionaries. The columns are found by name, and a row with a wrong number of fields stops the script.
    UTF-16 files keep lone surrogates (surrogatepass), so a pair that was cut stays visible."""
    errors = "surrogatepass" if encoding.startswith("utf-16") else "strict"
    with open(path, encoding=encoding, errors=errors, newline="") as f:
        rows = list(csv.reader(f, delimiter=delimiter, quoting=csv.QUOTE_NONE))
    header = [h.lstrip("﻿") for h in rows[0]]
    missing = [c for c in columns if c not in header]
    if missing:
        sys.exit("%s: missing columns %s" % (path, missing))
    table = []
    for number, row in enumerate(rows[1:], start=2):
        if len(row) != len(header):
            sys.exit("%s, line %d: %d fields, expected %d" % (path, number, len(row), len(header)))
        table.append(dict(zip(header, row)))
    return table


def starts_inside(text):
    """True when the first character belongs to the character before it."""
    c = text[0]
    o = ord(c)
    return (0xDC00 <= o <= 0xDFFF or unicodedata.combining(c) > 0 or c == ZWJ
            or 0xFE00 <= o <= 0xFE0F or 0x1F3FB <= o <= 0x1F3FF)


def ends_inside(text):
    """True when the last character waits for the next one: half of a pair, a joiner, or half of a flag.
    Every flag word of the export has an even number of regional indicators."""
    o = ord(text[-1])
    if 0xD800 <= o <= 0xDBFF or text[-1] == ZWJ:
        return True
    run = 0
    for c in reversed(text):
        if 0x1F1E6 <= ord(c) <= 0x1F1FF:
            run += 1
        else:
            break
    return run % 2 == 1


def check_wrap(cases_path, lines_path, label_limit=LABEL_LIMIT):
    cases = {}
    for row in read_table(cases_path, ["case", "text"], encoding="utf-16"):
        cases[int(row["case"])] = row["text"].replace("\\n", "\n").replace("\\t", " ")
    groups = {}
    columns = ["case", "width_limit", "line_no", "para", "width", "chars", "grown_width", "grown_chars", "text"]
    for row in read_table(lines_path, columns, encoding="utf-16"):
        case, limit, line_no, para, width, chars, gw, gc = (int(row[c]) for c in columns[:8])
        groups.setdefault((case, limit), []).append((line_no, para, width, chars, gw, gc, row["text"]))
    loss = wide = long_ = split = greedy = checked = rows = multi = 0
    cause = {}
    fill = {}
    for (case, limit), lines in sorted(groups.items()):
        rows += len(lines)
        original = "".join(cases[case].split())
        if "".join("".join(x[6].split()) for x in lines) != original:
            loss += 1
        for line_no, para, width, chars, gw, gc, text in lines:
            if text:
                fill.setdefault(limit, []).append((width, chars))
                if any(ord(c) > 0xFFFF or unicodedata.combining(c) or c == ZWJ for c in text):
                    multi += 1
                if starts_inside(text) or ends_inside(text):
                    split += 1
            if width > limit:
                wide += 1
            if chars > label_limit or chars != units(text):
                long_ += 1
        for a, b in zip(lines, lines[1:]):
            if a[1] != b[1] or a[6] == "" or b[6] == "":
                continue
            checked += 1
            if 0 <= a[4] <= limit and 0 <= a[5] <= label_limit:
                greedy += 1
            by = "width" if a[4] > limit else "cap"
            cause.setdefault(limit, {"width": 0, "cap": 0})[by] += 1
    print("cases %d, case x width groups %d, line rows %d" % (len(cases), len(groups), rows))
    print("lines that hold a character of several code units: %d" % multi)
    print("groups where characters were lost or added: %d" % loss)
    print("lines wider than the limit: %d" % wide)
    print("lines over %d UTF-16 units: %d" % (label_limit, long_))
    print("lines that start or end inside a character: %d" % split)
    print("line breaks checked for the greedy rule: %d" % checked)
    print("line breaks where the next word would fit: %d" % greedy)
    for limit in sorted(fill):
        widths = [x[0] for x in fill[limit]]
        chars = [x[1] for x in fill[limit]]
        full = [x[0] for x in fill[limit] if x[1] == label_limit]
        print("limit %4d px: %5d lines, mean width %6.1f px, mean %4.1f units, longest %d units, %d lines of exactly %d units, %s px wide on average" % (
            limit, len(widths), statistics.mean(widths), statistics.mean(chars), max(chars), len(full), label_limit,
            "%.1f" % statistics.mean(full) if full else "n/a"))
    for limit in sorted(cause):
        total = cause[limit]["width"] + cause[limit]["cap"]
        print("limit %4d px: %5d breaks, %5.1f%% decided by the width, %5.1f%% by the %d-unit cap" % (
            limit, total, 100.0 * cause[limit]["width"] / total, 100.0 * cause[limit]["cap"] / total, label_limit))
    return 0 if loss + wide + long_ + split + greedy == 0 else 1


def check_counts(path):
    table = {}
    for row in read_table(path, ["case", "width_limit", "lines_with_cap", "lines_without_cap"]):
        table.setdefault(int(row["width_limit"]), []).append((int(row["lines_with_cap"]), int(row["lines_without_cap"])))
    for limit in sorted(table):
        capped = statistics.mean(x[0] for x in table[limit])
        free = statistics.mean(x[1] for x in table[limit])
        print("limit %4d px: %.2f lines per text with the cap, %.2f without it (%+.1f%%)" % (limit, capped, free, 100.0 * (capped - free) / free))
    return 0


def read_bmp(path):
    data = open(path, "rb").read()
    offset = struct.unpack_from("<I", data, 10)[0]
    width, height, planes, bits = struct.unpack_from("<iiHH", data, 18)
    flip = height > 0
    height = abs(height)
    bytes_per = bits // 8
    stride = (width * bytes_per + 3) // 4 * 4
    rows = []
    for y in range(height):
        src = (height - 1 - y) if flip else y
        rows.append(data[offset + src * stride: offset + src * stride + width * bytes_per])
    return width, height, bytes_per, rows


def ink(rows, width, bpp, top, bottom, x_from=4, x_to=None):
    """Leftmost and rightmost dark pixel in a band of rows, (-1, -1) when there is none."""
    left, right = width, -1
    x_to = width - 4 if x_to is None else x_to
    for yy in range(max(top, 0), min(bottom, len(rows))):
        row = rows[yy]
        for x in range(x_from, x_to):
            p = row[x * bpp: x * bpp + 3]
            if p[0] < 140 and p[1] < 140 and p[2] < 140:
                left = min(left, x)
                right = max(right, x)
    return (left, right) if right >= 0 else (-1, -1)


def fields(line):
    """key=value pairs of a SHOT line. A value may contain spaces (font=Times New Roman), the text field is left out."""
    head = line.rstrip("\r\n").split(" text=")[0]
    return dict(re.findall(r"(\w+)=(.*?)(?= \w+=|$)", head))


def check_shot(bmp_path, journal_path, scene):
    width, height, bpp, rows = read_bmp(bmp_path)
    label_rows, type_rows = [], []
    for line in open(journal_path, encoding="utf-8", errors="replace"):
        if "SHOT row scene=%s " % scene in line:
            label_rows.append(fields(line))
        elif "SHOT type scene=%s " % scene in line:
            type_rows.append(fields(line))
    print("bmp %dx%d, %d bits, %d label rows and %d object rows in the journal" % (width, height, bpp * 8, len(label_rows), len(type_rows)))
    worst = 0
    per_font = {}
    for r in label_rows:
        y, x0, w, h = int(r["y"]), int(r["x"]), int(r["width"]), int(r["height"])
        left, right = ink(rows, width, bpp, y + 2, y + h)
        diff = right - x0 + 1 - w
        worst = max(worst, abs(diff))
        key = "%s %s" % (r["font"], r["points"])
        per_font.setdefault(key, []).append(diff)
        print("row y=%d %-20s units=%-3s TextGetSize width=%d, dark pixels from x=%d to x=%d, right edge minus expected %+d px" % (
            y, key, r["units"], w, left, right, diff))
    for key, diffs in per_font.items():
        print("font %-20s rows %d, right edge minus expected from %+d to %+d px" % (key, len(diffs), min(diffs), max(diffs)))
    ok = True
    if label_rows:
        print("largest difference: %d px (accepted up to %d)" % (worst, TOLERANCE_PX))
        ok = worst <= TOLERANCE_PX
    for r in type_rows:
        y, h = int(r["y"]), int(r["height"])
        if r.get("box", "none") != "none":
            # inside of the box only, 6 pixels away from its border
            x_from, x_to = (int(v) for v in r["box"].split("-"))
            left, right = ink(rows, width, bpp, y + 6, y + h - 6, x_from + 6, x_to - 6)
        else:
            left, right = ink(rows, width, bpp, y, y + h)
        ws, wt = int(r["width_stored"]), int(r["width_sent"])
        if right < 0:
            print("%-20s sent %s, stored %s units: no dark pixels" % (r["kind"], r["sent"], r["stored"]))
            continue
        drawn = right - left + 1
        nearer = "stored" if abs(drawn - ws) < abs(drawn - wt) else "sent"
        print("%-20s sent %s, stored %s units: dark pixels %d px wide, stored text %d px, sent text %d px, nearer to the %s text" % (
            r["kind"], r["sent"], r["stored"], drawn, ws, wt, nearer))
    return 0 if ok and (label_rows or type_rows) else 1


def check_cost(path):
    table = {}
    for row in read_table(path, ["scenario", "lines", "block", "run", "reps", "microseconds_per_call"], ","):
        table.setdefault((row["scenario"], int(row["lines"]), row["block"]), []).append(float(row["microseconds_per_call"]))
    for key in sorted(table):
        runs = table[key]
        print("%-6s lines=%-3d %-7s median %8.1f us   runs %s" % (key[0], key[1], key[2], statistics.median(runs), ", ".join("%.1f" % r for r in runs)))
    return 0


if __name__ == "__main__":
    mode = sys.argv[1] if len(sys.argv) > 1 else ""
    if mode == "wrap" and len(sys.argv) in (4, 5):
        sys.exit(check_wrap(sys.argv[2], sys.argv[3], int(sys.argv[4]) if len(sys.argv) == 5 else LABEL_LIMIT))
    if mode == "counts" and len(sys.argv) == 3:
        sys.exit(check_counts(sys.argv[2]))
    if mode == "shot" and len(sys.argv) == 5:
        sys.exit(check_shot(sys.argv[2], sys.argv[3], sys.argv[4]))
    if mode == "cost" and len(sys.argv) == 3:
        sys.exit(check_cost(sys.argv[2]))
    print(__doc__)
    sys.exit(2)
