#!/usr/bin/env python3
"""Rename PDFs by what they say: 2026-03-04_Copperline-Electric-Co-op_bill.pdf. Free, from brasspage.com/auto-rename-pdf/

Needs Python 3.9+, poppler (pdftotext, pdftoppm) and tesseract on your PATH. Reads page 1 only.
A PDF with a text layer is read directly. A scanned PDF (no text layer) gets OCR with Tesseract.

  python3 rename_pdfs.py FOLDER                          # dry run: prints old -> new, renames nothing
  python3 rename_pdfs.py FOLDER --senders senders.txt    # one known sender name per line (much better names)
  python3 rename_pdfs.py FOLDER --apply                  # renames, and logs each change to FOLDER/rename-log.csv
  python3 rename_pdfs.py FOLDER --undo                   # puts the old names back from that log
"""

from __future__ import annotations

import argparse
import csv
import difflib
import re
import subprocess
import sys
import tempfile
from pathlib import Path

MON = [
    "jan",
    "feb",
    "mar",
    "apr",
    "may",
    "jun",
    "jul",
    "aug",
    "sep",
    "oct",
    "nov",
    "dec",
]
M = r"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?"
DATE = re.compile(
    rf"\b(?:(?P<a>{M})\s+(?P<ad>\d{{1,2}})[,.]?\s*(?P<ay>\d{{4}})"
    rf"|(?P<bd>\d{{1,2}})\s+(?P<b>{M}),?\s+(?P<by>\d{{4}})"
    rf"|(?P<cy>\d{{4}})-(?P<cm>\d{{1,2}})-(?P<cd>\d{{1,2}})"
    rf"|(?P<dm>\d{{1,2}})/(?P<dd>\d{{1,2}})/(?P<dy>\d{{4}}|\d{{2}}))\b",
    re.IGNORECASE,
)
ISSUE = re.compile(
    r"(statement|bill|invoice|notice|issue|receipt|letter)?\s*date( of issue| issued)?\s*:?\s*$",
    re.IGNORECASE,
)
NOT_ISSUE = re.compile(
    r"\b(due|pay|respond|period|from|since|service|before|starting|until|through|claim|message)\b",
    re.IGNORECASE,
)
KINDS = [
    "invoice",
    "receipt",
    "statement",
    "bill",
    "notice",
]  # no match and "Dear ..." -> letter


def text_of(pdf: Path) -> tuple[str, str]:
    t = subprocess.run(
        ["pdftotext", "-layout", "-l", "1", pdf, "-"],
        capture_output=True,
        text=True,
        check=False,
    ).stdout
    if len(re.sub(r"\s", "", t)) >= 30:
        return t, "text layer"
    with tempfile.TemporaryDirectory() as tmp:
        subprocess.run(
            [
                "pdftoppm",
                "-r",
                "300",
                "-gray",
                "-png",
                "-singlefile",
                "-l",
                "1",
                pdf,
                f"{tmp}/p",
            ],
            check=True,
        )
        ocr = subprocess.run(
            ["tesseract", f"{tmp}/p.png", "-", "--psm", "3"],
            capture_output=True,
            text=True,
            check=False,
        )
    return ocr.stdout, "ocr"


def iso(m: re.Match) -> str | None:
    g = m.groupdict()
    if g["a"] or g["b"]:
        mon, day, year = (
            MON.index((g["a"] or g["b"])[:3].lower()) + 1,
            int(g["ad"] or g["bd"]),
            int(g["ay"] or g["by"]),
        )
    elif g["cy"]:
        year, mon, day = int(g["cy"]), int(g["cm"]), int(g["cd"])
    else:  # numbers with slashes are read as US month/day
        mon, day, year = int(g["dm"]), int(g["dd"]), int(g["dy"])
        year += 2000 if year < 100 else 0
    return (
        f"{year:04d}-{mon:02d}-{day:02d}"
        if 1 <= mon <= 12 and 1 <= day <= 31 and 1990 < year < 2100
        else None
    )


def pick_date(text: str) -> str | None:
    # (score, date): a labeled issue date beats a date alone on its line beats any other date.
    best = None
    for line in text.splitlines():
        prev = 0
        for m in DATE.finditer(line):
            d = iso(m)
            # The label is the text since the last date, in its own column,
            # cut to its last 3 words: OCR text can join a box's lines into one.
            label = re.split(r"\s{3,}", line[prev : m.start()])[-1]
            label = " ".join(label.split()[-3:])
            prev = m.end()
            if not d or NOT_ISSUE.search(label):
                continue
            score = (
                3
                if ISSUE.search(label)
                else 2
                if not line.replace(m.group(), "").strip()
                else 1
            )
            if best is None or score > best[0]:
                best = (score, d)
    return best[1] if best else None


def squash(s: str) -> str:
    return re.sub(r"[^a-z0-9]", "", s.lower())


def pick_sender(text: str, senders: list[str]) -> str | None:
    # With a list: the closest known name anywhere on the page, if it is close enough to survive OCR typos.
    if senders:
        flat, best = squash(text), (0.0, None)
        for name in senders:
            n = squash(name)
            for i in range(max(1, len(flat) - len(n) + 1)):
                sm = difflib.SequenceMatcher(None, n, flat[i : i + len(n)])
                if sm.quick_ratio() > best[0] and sm.ratio() > best[0]:
                    best = (sm.ratio(), name)
        return best[1] if best[0] >= 0.8 else None
    # No list: the first line of words, as the letterhead usually comes first.
    for line in text.splitlines():
        line = re.split(r"\s{3,}", line.strip())[0]
        if len(re.findall(r"[A-Za-z]{2,}", line)) >= 2 and not re.search(r"\d|@", line):
            return line
    return None


def pick_kind(text: str) -> str:
    low = text.lower()
    # A short title line such as "Electric bill" or "INVOICE".
    for line in low.splitlines():
        if len(line.split()) <= 4:
            for k in KINDS:
                if re.search(rf"\b{k}\b", line):
                    return k
    if re.search(r"^\s*dear\b", low, re.MULTILINE):
        return "letter"
    hits = [(m.start(), k) for k in KINDS for m in [re.search(rf"\b{k}\b", low)] if m]
    return min(hits)[1] if hits else "document"


def name_for(text: str, senders: list[str]) -> str:
    sender = pick_sender(text, senders) or "unknown"
    slug = "-".join(re.findall(r"[A-Za-z0-9]+", sender))[:40] or "unknown"
    return f"{pick_date(text) or 'nodate'}_{slug}_{pick_kind(text)}"


def main() -> None:
    ap = argparse.ArgumentParser(
        description="Rename PDFs by their date, sender and kind."
    )
    ap.add_argument("folder", type=Path)
    ap.add_argument(
        "--senders", type=Path, help="text file, one known sender name per line"
    )
    ap.add_argument(
        "--apply", action="store_true", help="rename the files (default: dry run)"
    )
    ap.add_argument(
        "--undo", action="store_true", help="put the old names back from rename-log.csv"
    )
    a = ap.parse_args()
    log = a.folder / "rename-log.csv"
    if a.undo:
        if not log.exists():
            sys.exit(f"No log at {log}: nothing to undo.")
        for old, new in reversed(list(csv.reader(log.open()))[1:]):
            if (a.folder / new).exists() and not (a.folder / old).exists():
                (a.folder / new).rename(a.folder / old)
                print(f"{new} -> {old}")
        # Keep the log under a new name, so a later --undo never replays these rows.
        done, n = log.with_name("rename-log-undone.csv"), 2
        while done.exists():  # never overwrite an older one
            done, n = log.with_name(f"rename-log-undone_{n}.csv"), n + 1
        log.rename(done)
        return
    senders = (
        [s.strip() for s in a.senders.read_text().splitlines() if s.strip()]
        if a.senders
        else []
    )
    pdfs = sorted(p for p in a.folder.iterdir() if p.suffix.lower() == ".pdf")
    taken = {
        p.name.lower() for p in a.folder.iterdir()
    }  # lower case: Mac and Windows disks ignore case
    out = None
    if a.apply:
        new_log = not log.exists()
        fh = log.open("a", newline="")
        out = csv.writer(fh)
        if new_log:
            out.writerow(["old", "new"])
    for pdf in pdfs:
        try:
            text, how = text_of(pdf)
        except subprocess.CalledProcessError:
            # A broken or locked PDF: skip it, keep going.
            print(f"{pdf.name}: could not read, skipped")
            continue
        base = name_for(text, senders)
        new, n = f"{base}.pdf", 2
        # Never overwrite: add _2, _3 ...
        while new.lower() in taken and new.lower() != pdf.name.lower():
            new, n = f"{base}_{n}.pdf", n + 1
        taken.add(new.lower())
        print(f"{pdf.name} -> {new}  ({how})")
        if out and new != pdf.name:
            # Logged and flushed before the rename, so --undo works even after a crash.
            out.writerow([pdf.name, new])
            fh.flush()
            pdf.rename(a.folder / new)
    if not a.apply:
        print("Dry run: nothing renamed. Add --apply to rename.", file=sys.stderr)


if __name__ == "__main__":
    main()
