#!/usr/bin/env python3
"""Check a CSV file before and after translation. Standard library only.

  python3 csv_check.py inspect products.csv
  python3 csv_check.py split products.csv --translate name,description
  python3 csv_check.py merge products.csv products.to-translate.translated.csv
  python3 csv_check.py compare products.csv products.translated.csv

inspect  reports encoding, delimiter, rows, blank lines, ragged rows and
         cells with line breaks, then classifies every column: digits-only
         columns, and columns whose values look like codes, URLs, emails,
         language codes or formulas.
split    writes <name>.to-translate.csv: a digits-only row_id column plus the
         columns you name, as UTF-8 with a byte order mark. Translate that
         file, not the original.
merge    puts the translated columns back into the original by row_id and
         writes <name>.merged.csv with the original delimiter, as UTF-8 (with
         a byte order mark if the original had one or was not UTF-8).
compare  checks that a translated file kept the shape of the original: same
         header, same number of rows and columns, empty cells still empty,
         and the same values in every column you pass to --keep.

Exit code 0 means no problems, 1 means problems were printed.
"""
import argparse
import csv
import io
import re
import sys
from pathlib import Path

BOM = b"\xef\xbb\xbf"
DELIMS = [",", ";", "\t", "|"]
PATTERNS = [
    ("formula", re.compile(r"^[=+\-@]\S")),
    ("url", re.compile(r"^(https?://|www\.)\S+$", re.I)),
    ("email", re.compile(r"^[^@\s]+@[^@\s]+\.[a-z]{2,}$", re.I)),
    ("language code", re.compile(r"^[a-z]{2,3}([-_][A-Za-z]{2,4})?$")),
    ("code", re.compile(r"^(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9][A-Za-z0-9._/-]*$")),
]
DIGITS_ONLY = re.compile(r"^[\d\s.,:;/\-+()%]*$")


class Loaded:
    def __init__(self, path):
        raw = Path(path).read_bytes()
        self.path = path
        self.bom = raw.startswith(BOM)
        body = raw[len(BOM):] if self.bom else raw
        try:
            self.text = body.decode("utf-8")
            self.encoding = "utf-8-sig" if self.bom else "utf-8"
        except UnicodeDecodeError:
            try:
                self.text = body.decode("cp1252")
            except UnicodeDecodeError:
                sys.exit(f"{path}: neither UTF-8 nor Windows-1252. Re-save it as UTF-8 first.")
            self.encoding = "cp1252"
        self.delimiter = sniff(self.text)
        reader = csv.reader(io.StringIO(self.text, newline=""), delimiter=self.delimiter)
        self.all_rows = list(reader)
        self.blank_lines = sum(1 for r in self.all_rows if not any(c.strip() for c in r))
        self.rows = [r for r in self.all_rows if any(c.strip() for c in r)]
        self.header = self.rows[0] if self.rows else []
        self.data = self.rows[1:]


def sniff(text):
    sample = text[:20000]
    try:
        return csv.Sniffer().sniff(sample, delimiters="".join(DELIMS)).delimiter
    except csv.Error:
        first = sample.splitlines()[0] if sample else ""
        return max(DELIMS, key=first.count)


def name_of(delim):
    return {",": "comma", ";": "semicolon", "\t": "tab", "|": "pipe"}[delim]


def classify(values):
    filled = [v.strip() for v in values if v.strip()]
    if not filled:
        return "empty", []
    if all(DIGITS_ONLY.match(v) for v in filled):
        return "digits only", []
    flags = []
    for label, pat in PATTERNS:
        hits = [v for v in filled if pat.match(v)]
        if hits:
            flags.append(f"{label} ({len(hits)}/{len(filled)}, e.g. {hits[0][:40]!r})")
    return "text", flags


def cmd_inspect(a):
    f = Loaded(a.file)
    problems = 0
    enc = f.encoding
    if enc == "cp1252":
        enc = "not UTF-8 (read as Windows-1252; re-save it as UTF-8 before translating)"
        problems += 1
    elif not f.bom and any(ord(ch) > 127 for ch in f.text):
        enc = "utf-8 without a byte order mark (save it with one, or use split, so the encoding is not guessed)"
        problems += 1
    print(f"File:       {f.path}")
    label = enc.replace("utf-8-sig", "UTF-8").replace("utf-8", "UTF-8")
    print(f"Encoding:   {label}{' with byte order mark' if f.bom else ''}")
    print(f"Delimiter:  {name_of(f.delimiter)}")
    print(f"Rows:       1 header + {len(f.data)} data rows, {f.blank_lines} blank line(s)")
    width = len(f.header)
    ragged = [i + 2 for i, r in enumerate(f.data) if len(r) != width]
    if ragged:
        problems += 1
        print(f"Ragged:     rows {ragged[:10]} do not have {width} columns")
    multiline = sum(1 for r in f.data for c in r if "\n" in c or "\r" in c)
    if multiline:
        print(f"Line breaks inside cells: {multiline} (keep them quoted; do not paste this file into a text box)")
    print("\nColumns (the header row itself is shown, not judged):")
    for i, h in enumerate(f.header):
        kind, flags = classify([r[i] if i < len(r) else "" for r in f.data])
        note = "; ".join(flags)
        print(f"  {i + 1:>2}. {h[:30]!r:<32} {kind}{'  -> ' + note if note else ''}")
        if flags:
            problems += 1
    return 1 if problems else 0


def write_rows(path, rows, delimiter, encoding):
    with open(path, "w", encoding=encoding, newline="") as out:
        csv.writer(out, delimiter=delimiter).writerows(rows)


def cmd_split(a):
    f = Loaded(a.file)
    want = [c.strip() for c in a.translate.split(",")]
    missing = [c for c in want if c not in f.header]
    if missing:
        sys.exit(f"Not in header: {missing}. Header is {f.header}")
    idx = [f.header.index(c) for c in want]
    rows = [["row_id"] + want]
    for n, r in enumerate(f.data, start=1):
        rows.append([str(n)] + [r[i] if i < len(r) else "" for i in idx])
    out = Path(a.file).with_suffix(".to-translate.csv")
    write_rows(out, rows, ",", "utf-8-sig")
    print(f"Wrote {out}: row_id + {want}, {len(rows) - 1} rows, UTF-8 with a byte order mark. Translate this file.")
    return 0


def cmd_merge(a):
    f = Loaded(a.original)
    t = Loaded(a.translated)
    if not t.header or t.header[0] != "row_id":
        sys.exit("The translated file must start with the row_id column written by split.")
    by_id = {r[0]: r for r in t.data if r}
    problems = 0
    if len(by_id) != len(f.data):
        problems += 1
        print(f"Row count differs: original {len(f.data)}, translated {len(by_id)}")
    cols = [(j, t.header[j]) for j in range(1, len(t.header)) if t.header[j] in f.header]
    short = [n + 1 for n, r in enumerate(f.data, start=1) if len(r) < len(f.header)]
    if short:
        sys.exit(f"Rows {short[:10]} of {a.original} have fewer columns than the header. Fix them first (run inspect).")
    out_rows = [f.header]
    for n, r in enumerate(f.data, start=1):
        r = list(r)
        tr = by_id.get(str(n))
        if tr is None:
            problems += 1
            print(f"row_id {n} missing from the translated file; kept the original row")
        else:
            for j, col in cols:
                r[f.header.index(col)] = tr[j] if j < len(tr) else ""
        out_rows.append(r)
    out = Path(a.original).with_suffix(".merged.csv")
    # A non-UTF-8 original is written as UTF-8 with a byte order mark: a translation can
    # contain characters the old encoding cannot store.
    enc = "utf-8" if f.encoding == "utf-8" else "utf-8-sig"
    write_rows(out, out_rows, f.delimiter, enc)
    print(f"Wrote {out} with {name_of(f.delimiter)} delimiter, encoding {enc}.")
    return 1 if problems else 0


def cmd_compare(a):
    o = Loaded(a.original)
    t = Loaded(a.translated)
    keep = [c.strip() for c in (a.keep or "").split(",") if c.strip()]
    unknown = [c for c in keep if c not in o.header]
    if unknown:
        sys.exit(f"--keep names columns that are not in the header: {unknown}. Header is {o.header}")
    problems = []
    if o.delimiter != t.delimiter:
        print(f"Note: delimiter changed from {name_of(o.delimiter)} to {name_of(t.delimiter)}")
    if o.bom != t.bom:
        print(f"Note: byte order mark {'removed' if o.bom else 'added'}")
    if o.header != t.header:
        problems.append(f"Header differs: {o.header} vs {t.header}")
    if len(o.data) != len(t.data):
        problems.append(f"Data rows: original {len(o.data)}, translated {len(t.data)}")
    for n, (ro, rt) in enumerate(zip(o.data, t.data), start=2):
        if len(ro) != len(rt):
            problems.append(f"Row {n}: {len(ro)} columns became {len(rt)}")
            continue
        for i, (co, ct) in enumerate(zip(ro, rt)):
            col = o.header[i] if i < len(o.header) else f"#{i + 1}"
            if not co.strip() and ct.strip():
                problems.append(f"Row {n}, {col}: empty cell now has {ct[:40]!r}")
            elif co.strip() and not ct.strip():
                problems.append(f"Row {n}, {col}: text disappeared")
            elif col in keep and co != ct:
                problems.append(f"Row {n}, {col}: {co[:40]!r} changed to {ct[:40]!r}")
    unchanged = {}
    for ro, rt in zip(o.data, t.data):
        for i, (co, ct) in enumerate(zip(ro, rt)):
            col = o.header[i] if i < len(o.header) else f"#{i + 1}"
            if col not in keep and co.strip() and co == ct and not DIGITS_ONLY.match(co):
                unchanged[col] = unchanged.get(col, 0) + 1
    for p in problems[:50]:
        print("PROBLEM:", p)
    if len(problems) > 50:
        print(f"... and {len(problems) - 50} more")
    for col, n in unchanged.items():
        print(f"Check: {n} text cell(s) in {col!r} are identical to the original (untranslated, or a name/code)")
    print("OK: same shape" if not problems else f"{len(problems)} problem(s)")
    return 1 if problems else 0


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    s = p.add_subparsers(dest="cmd", required=True)
    s.add_parser("inspect").add_argument("file")
    sp = s.add_parser("split")
    sp.add_argument("file")
    sp.add_argument("--translate", required=True, help="comma-separated column names to translate")
    mp = s.add_parser("merge")
    mp.add_argument("original")
    mp.add_argument("translated")
    cp = s.add_parser("compare")
    cp.add_argument("original")
    cp.add_argument("translated")
    cp.add_argument("--keep", help="comma-separated columns that must not change")
    a = p.parse_args()
    sys.exit({"inspect": cmd_inspect, "split": cmd_split, "merge": cmd_merge, "compare": cmd_compare}[a.cmd](a))


if __name__ == "__main__":
    main()
