#!/usr/bin/env python3
"""Genera desde D1 el fichero de erratas del impreso que se reproducen aposta.

Por que generado y no escrito a mano. La misma lista vive en la tabla
`print_errata`, en la pagina publica /print-errata/ y en el repo del texto. Con
copias a mano, la primera errata que se anada las descuadra. Aqui la tabla es la
unica fuente y el fichero se rehace de ella.

Donde va. A la RAIZ de `vedabase-original`, que es el repo del texto. No es un
informe: es el criterio editorial puesto donde lo va a leer quien edite el texto.
Sin el, cualquiera que clone el repo «arreglara» `conquerer` o `harrassed` de
buena fe, que es exactamente lo que este proyecto deshace.

Uso: python3 generar_erratas_md.py [--salida <ruta>]
"""
import re, sys, pathlib

HERE = pathlib.Path(__file__).resolve().parent
REPO = pathlib.Path('/Users/jaganat/git_projects/vedabase-original')
sys.path.insert(0, str(HERE))
from sincronizar_diff import d1

GRUPOS = [
    ('gloss', 'Glosses that change the meaning',
     'The ones most likely to mislead: a reader learning Sanskrit takes away the '
     'meaning printed here.'),
    ('fact', 'Factual error', ''),
    ('name', 'Proper names and Sanskrit terms deformed in print',
     'Where it helps, the note gives the form used elsewhere in these books.'),
    ('grammar', 'Broken grammar and misquotations', ''),
    ('spelling', 'Misspellings',
     'No reader is misled by these; the first printings had their typos and the '
     'typos remain.'),
    ('numbering', 'Skipped numbering', ''),
]


def etiqueta(ref, title=None):
    p = ref.split('/')
    if re.fullmatch(r'0[a-z]\d*', p[-1]) and title:
        ab = {'sb': 'SB', 'bg': 'Bg.', 'cc': 'CC', 'tlc': 'TLC', 'tqk': 'TQK',
              'ekc': 'EKC', 'ej': 'EJ', 'nod': 'NOD', 'kb': 'KB', 'lob': 'LOB',
              'iso': 'ĪŚO', 'ssr': 'SSR'}.get(p[0], p[0].upper())
        return f"{ab} — {title.splitlines()[0][:40]}"
    if p[0] == 'sb' and p[1].isdigit(): return 'SB ' + '.'.join(p[1:])
    if p[0] == 'bg': return 'Bg. ' + '.'.join(p[1:])
    if p[0] == 'cc':
        lila = {'adi': 'Ādi', 'madhya': 'Madhya', 'antya': 'Antya'}.get(p[1], p[1])
        return f"CC {lila} " + '.'.join(p[2:])
    ab = {'tlc': 'TLC', 'tqk': 'TQK', 'ekc': 'EKC', 'ej': 'EJ', 'nod': 'NOD',
          'kb': 'KB', 'lob': 'LOB', 'poy': 'POY', 'pop': 'POP', 'tys': 'TYS',
          'iso': 'ĪŚO', 'ssr': 'SSR'}.get(p[0], p[0].upper())
    return f"{ab} " + '.'.join(p[1:])


def celda(s):
    return (s or '').replace('|', '\\|').replace('*', '').strip()


def orden(x):
    lab = etiqueta(x['ref'], x.get('title'))
    libro = re.match(r'[A-Za-zĀāŚśĪī.]+', lab)
    return (libro.group(0) if libro else lab, [int(n) for n in re.findall(r'\d+', lab)])


def main():
    salida = pathlib.Path(sys.argv[sys.argv.index('--salida') + 1]) \
        if '--salida' in sys.argv else REPO / 'PRINT_ERRATA.md'
    filas = d1("SELECT e.ref, e.kind, e.digital, e.printed, e.page, e.note, "
               "v.translation AS title FROM print_errata e "
               "LEFT JOIN verses v ON v.ref = e.ref AND v.lang = 'en' "
               "ORDER BY e.kind, e.ref", js=True)
    n = len(filas)

    out = [f"""# Errors in the print, reproduced on purpose

**This file is generated. Do not edit it by hand** — it is written from the
`print_errata` table in D1 by `astro_vedabase/scripts/scan_audit/generar_erratas_md.py`,
which is also what feeds <https://vedabase.cc/print-errata/>.

## What it is for

This repository holds the text of Śrīla Prabhupāda's first editions, checked line
by line against scans of the printed pages. Where the two differed, the paper won.

The paper is not always right. A first edition has typos, misspelled names, a
gloss that says the opposite of what the word means. **Those are reproduced too.**
What the reader gets is the book as it was printed, not the book as it should
have been printed.

So: **the {n} entries below are deliberate.** If you are editing this repository
and find `conquerer`, `harrassed` or `Janamcjaya`, do not fix them. They are what
the page says, verified against the image — in most cases at 400–600 dpi — before
being written.

The one exception the rule allows is the print contradicting itself inside the
same sentence. A line that printed twice because a plate slipped is damage to the
copy, not a reading, and is not reproduced.

## A floor, not a total

This list is what the collation *found*, and the method has a blind spot worth
stating: it can only surface an errata where the digital text and the scan
**differ**. An errata that the digital text had carried from the start produces
no divergence, so it never comes up. These {n} are the print's errors that someone
had silently corrected and we have put back — not every error in the print.
The list grows as the audit continues.
"""]

    for kind, titulo, intro in GRUPOS:
        sub = sorted([f for f in filas if f['kind'] == kind], key=orden)
        if not sub: continue
        out.append(f"\n## {titulo} ({len(sub)})\n")
        if intro: out.append(f"{intro}\n")
        out.append("| Reference | Digital text had | Print reads — and this is what we serve | Page |")
        out.append("|---|---|---|---|")
        for f in sub:
            nota = f" <br><sub>{celda(f['note'])}</sub>" if f.get('note') else ''
            out.append(f"| {etiqueta(f['ref'], f.get('title'))} "
                       f"| {celda(f['digital'])[:70]} "
                       f"| **{celda(f['printed'])[:70]}**{nota} "
                       f"| {('p. ' + f['page']) if f.get('page') else '—'} |")

    out.append("""
---

## What is not on this list

**Repeated lines.** When a plate slipped and a line printed twice, that is a
defect of the copy, not a reading. It is not reproduced.

**Places where the print was right.** Most corrections in `corrections.jsonl` run
the other way: the error was in the digital text and the paper had it right.

**Readings of the first edition.** "Mohammedans" where the revision put
"Muslims", "Kuvera" for "Kubera", "Chaitanya" for "Caitanya": these are not
errata. They are the reading of the first edition, which is the whole point.

**Diacritics and punctuation.** OCR is not a reliable witness to either — a full
pass produced 24,035 candidates and not one was actionable. Nothing there is
changed without looking at the image.

## Rebuilding this file

    python3 astro_vedabase/scripts/scan_audit/generar_erratas_md.py
""")
    salida.write_text('\n'.join(out) + '\n', encoding='utf-8')
    print(f'  {salida}  ({n} erratas)')
    return 0


if __name__ == '__main__':
    sys.exit(main())
