"""Turn table cells that hold numbers or dates as text into real Excel numbers and dates.

Usage: python fix_numbers.py <in.xlsx | in.md | in.csv> [out.xlsx] [--day-first]
Needs openpyxl (pip install openpyxl). Writes out.xlsx (default: <in>-fixed.xlsx).
Numbers: 1,234.56  $1,234.56  (1,234.56)  -1,234.56  1,234.56-  +200  12.5%  (US style: comma groups, dot decimals).
Dates: 2026-03-14 and 03/14/2026 (14/03/2026 with --day-first).
Codes with a leading zero (00412, 02134) stay text, and so does the rest of their column (a ZIP column stays text).
Any other cell stays as it is.
It prints each cell that stayed text in a column where most cells became numbers: often an OCR misread.
From brasspage.com/scanned-pdf-to-excel/ (MIT license).
"""

import csv
import re
import sys
from datetime import datetime
from pathlib import Path

from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter

NUM = re.compile(
    r"^(\()?([+-])?(\$)?\s?(\d{1,3}(?:,\d{3})+|\d+)?(\.\d+)?(%)?(-)?(\))?$"
)


def number(s):
    m = NUM.match(s)
    if not m or not (m[4] or m[5]) or bool(m[1]) != bool(m[8]):
        return None
    if m[4] and len(m[4]) > 1 and m[4][0] == "0":
        return None  # 00412 is a code, not 412
    v = float((m[4] or "0").replace(",", "") + (m[5] or ""))
    if m[1] or m[2] == "-" or m[7]:
        v = -v
    fmt = ("#,##0" if "," in (m[4] or "") else "0") + (
        "." + "0" * (len(m[5]) - 1) if m[5] else ""
    )
    if m[6]:
        return v / 100, fmt + "%"
    if m[3]:
        fmt = '"$"' + fmt
    return v, f"{fmt};({fmt})" if m[1] else fmt


def when(s, day_first):
    for f, shown in (
        ("%Y-%m-%d", "yyyy-mm-dd"),
        ("%d/%m/%Y", "dd/mm/yyyy") if day_first else ("%m/%d/%Y", "mm/dd/yyyy"),
    ):
        try:
            return datetime.strptime(s, f), shown  # noqa: DTZ007 (Excel dates have no time zone)
        except ValueError:
            pass
    return None


def md_tables(text):
    tables, cur = [], []
    for line in text.splitlines() + [""]:
        line = line.strip()
        if line.startswith("|"):
            if not set(line.replace(" ", "")) <= set("|-:"):
                cur.append(
                    [
                        c.strip().replace("\\|", "|")
                        for c in re.split(r"(?<!\\)\|", line.strip("|"))
                    ]
                )
        elif cur:
            tables.append(cur)
            cur = []
    return tables


def load(path):
    if path.suffix.lower() == ".xlsx":
        return load_workbook(path)
    wb = Workbook()
    wb.remove(wb.active)
    if path.suffix.lower() == ".csv":
        with path.open(newline="", encoding="utf-8-sig") as f:
            tables = [list(csv.reader(f))]
    else:
        tables = md_tables(path.read_text(encoding="utf-8"))
    for i, rows in enumerate(tables, 1):
        ws = wb.create_sheet(f"Table {i}")
        for r in rows:
            ws.append(r)
    return wb


def fix(wb, day_first=False):
    nums = dates = 0
    for ws in wb.worksheets:
        cols = {}
        codes = {
            c.column
            for row in ws.iter_rows()
            for c in row
            if isinstance(c.value, str) and re.fullmatch(r"0\d+", c.value.strip())
        }
        for row in ws.iter_rows():
            for c in row:
                if (
                    not isinstance(c.value, str)
                    or not c.value.strip()
                    or c.column in codes
                ):
                    continue
                s = c.value.strip()
                got = number(s) or when(s, day_first)
                k = cols.setdefault(c.column, [0, []])
                if got is None:
                    k[1].append(c)
                    continue
                c.value, c.number_format = got
                k[0] += 1
                nums += isinstance(got[0], float)
                dates += isinstance(got[0], datetime)
        for col, (n, text) in cols.items():
            for c in (
                text[1:] if n > len(text) else []
            ):  # the first text cell is usually the header
                print(
                    f"check {ws.title}!{get_column_letter(col)}{c.row}: {c.value!r} stayed text"
                )
    return nums, dates


def main(argv):
    day_first = "--day-first" in argv
    args = [a for a in argv if a != "--day-first"]
    if not args:
        sys.exit(__doc__)
    src = Path(args[0])
    out = Path(args[1]) if len(args) > 1 else src.with_name(src.stem + "-fixed.xlsx")
    wb = load(src)
    if not wb.worksheets:
        sys.exit(f"no table found in {src}")
    nums, dates = fix(wb, day_first)
    wb.save(out)
    print(f"{out}: {nums} numbers, {dates} dates")


if __name__ == "__main__":
    main(sys.argv[1:])
