"""Audit the workbook against its own typographic conventions.

The conventions state four rules: italic for file, folder and dataset names,
bold for commands and buttons, monospace for code, column names, variable
names and web addresses, and the bare form "Section 4.4" for a cross
reference into the book. This reads the source and reports where a token
appears outside the form its own rule sets.

Code fences, image lines and captions are skipped, since a fenced block is
already code and an alt attribute carries no styling at all.

usage: python typo_audit.py <workbook.md>
"""
import re
import sys
from pathlib import Path

FILE = re.compile(r"(?<![\w*`/.])([A-Za-z][\w\-]*\.(?:py|csv|json|docx|geojson"
                  r"|png|txt|zip|md|imscc))(?![\w*`])")
CODEY = re.compile(r"(?<![\w*`])(pct_pov|pct_nv|pct65|medinc|hh_nv|pov_univ|"
                   r"CV_LIMIT|TOLERANCE|BUDGETS|WEIGHTINGS|EXPLORE|STRONG|"
                   r"MIN_BG|LAG_SWEEP|NOISE_LEVELS|CONTROL_SIGMA|SEED|"
                   r"ASI_WEIGHTS|GRID|Ws\[|need_index|build_weights|asi\()"
                   r"(?![\w*`])")
CMD = re.compile(r"\btype\s+(?!\*\*)([a-z]+\s+[\w./\-]+\.py)")


def main():
    src = Path(sys.argv[1])
    lines = src.read_text(encoding="utf-8").split("\n")
    fenced = False
    hits = {"file not italic": [], "code not monospaced": [],
            "command not bold": []}
    for i, ln in enumerate(lines, 1):
        if ln.strip().startswith("```"):
            fenced = not fenced
            continue
        if fenced or ln.strip().startswith("!["):
            continue
        for m in FILE.finditer(ln):
            before = ln[max(0, m.start() - 1):m.start()]
            after = ln[m.end():m.end() + 1]
            if before == "*" and after == "*":
                continue
            if before == "`" or after == "`":
                continue
            hits["file not italic"].append((i, m.group(1), ln.strip()[:90]))
        for m in CODEY.finditer(ln):
            hits["code not monospaced"].append((i, m.group(1),
                                                ln.strip()[:90]))
        for m in CMD.finditer(ln):
            hits["command not bold"].append((i, m.group(1), ln.strip()[:90]))

    for k, v in hits.items():
        print(f"\n{k.upper()}: {len(v)}")
        for ln_no, tok, ctx in v[:12]:
            print(f"  line {ln_no:5d}  {tok:28} {ctx}")
        if len(v) > 12:
            print(f"  ... and {len(v) - 12} more")
    print(f"\ntotal findings: {sum(len(v) for v in hits.values())}")


if __name__ == "__main__":
    main()
