import re
p = 'backend/app/services/citations.py'
s = open(p).read()

s = s.replace('''An entry is one book at one page, headed by what that page was read for:

    Periventricular leukomalacia (imaging) — Merrow AC, Carlson A. Diagnostic
    Imaging: Pediatrics, 3rd ed., 2017, p. 1099.

Two pages of the same book are two entries, because they are two different
places to look. Collapsing them into `Nelson, pp. 1069, 1071, 3727` saves a
line and costs the reader the thing the list is for.
"""''',
'''An entry is one book, written the standard way:

    Kliegman R, St Geme JW, Blum NJ, et al., eds. Nelson Textbook of
    Pediatrics. 22nd ed. Elsevier; 2024.

One line per book, whatever number of passages came from it — forty chunks of
Nelson is one reference, and a list that repeats a book is noise standing
where provenance should be. Page numbers stay in the stored entry for anybody
tracing a passage back; they are offsets into one particular ebook build, and
`p. 3722` in front of a reader is a number they cannot use.
"""''')

# publisher restored as the fifth part
s = s.replace('''#: authors, title, edition, year. Assembled rather than stored whole so every
#: line reads the same and the page can be added at the end.
BOOKS: dict[str, tuple[str, str, str, str]] = {''',
'''#: authors, title, edition, publisher, year. Assembled from parts rather than
#: stored whole so every line comes out in the same order with the same
#: punctuation, however uneven the corpus's own naming is.
BOOKS: dict[str, tuple[str, str, str, str, str]] = {''')

AAP = "American Academy of Pediatrics"
PUB = {
    "Nelson": "Elsevier", "Nelson review": "Elsevier", "Nelson antimicrobial": AAP,
    "Fleisher": "Wolters Kluwer", "CURRENT": "McGraw Hill", "MedStudy": "MedStudy",
    "Netter": "Elsevier", "Zitelli": "Elsevier", "Berkowitz": AAP,
    "Board guide": "Springer", "Lissauer": "Elsevier", "Signs and symptoms": AAP,
    "Ghai": "CBS Publishers", "Algorithms": "Jaypee Brothers", "Gomella": "McGraw Hill",
    "AAP policies": AAP, "Hospitalized child": AAP, "Imaging": "Elsevier",
    "GI textbook": "Springer", "Update": "Springer", "Decision making": "Elsevier",
    "Harriet Lane": "Elsevier", "ICD": AAP, "Red Book": AAP, "Red Book atlas": AAP,
    "AAP nutrition": AAP, "Practitioner": "Jaypee Brothers", "Developmental": AAP,
    "Pulmonology": AAP, "Environmental": AAP, "Dentistry": "Elsevier", "Cardiac": AAP,
    "EM": "Elsevier", "Challenging cases": AAP, "Clinician nutrition": AAP,
    "PPE": AAP, "GI algorithms": "Karger", "ENT": AAP, "NRP": AAP, "Plastics": AAP,
    "Depression": AAP, "Asthma guide": AAP, "Breastfeeding": AAP,
    "Asthma chart": AAP, "Coding": AAP, "Telehealth": AAP,
}

# Insert the publisher before the year in each tuple.
def add_publisher(match):
    key = match.group(1)
    body = match.group(2)
    parts = re.findall(r'"((?:[^"\\\\]|\\\\.)*)"', body)
    if len(parts) != 4 or key not in PUB:
        return match.group(0)
    authors, title, edition, year = parts
    lines = [f'    "{key}": ({_q(authors)}, {_q(title)}, {_q(edition)},',
             f'             {_q(PUB[key])}, {_q(year)}),']
    return "\n".join(lines)

def _q(text):
    return '"' + text.replace('"', '\\"') + '"'

start = s.index('BOOKS: dict[str, tuple[str, str, str, str, str]] = {')
end = s.index('}\n\n\ndef book_line', start)
block = s[start:end]
head, body = block.split('{', 1)
rebuilt = [head + '{']
for match in re.finditer(r'^    "([^"]+)": \(([\s\S]*?)\),$', body, re.M):
    rebuilt.append(add_publisher(match))
rebuilt_text = "\n".join(rebuilt) + "\n"
s = s[:start] + rebuilt_text + s[end:]

s = s.replace('''def book_line(key: str) -> str:
    """`Kliegman R, ed. Nelson Textbook of Pediatrics, 22nd ed., 2024`"""
    authors, title, edition, year = BOOKS[key]
    tail = ", ".join(part for part in (edition, year) if part)
    # A corporate author has no "eds." to end it, so it runs straight into the
    # title — "American Academy of Pediatrics Pediatric Clinical Practice…".
    stop = "" if not authors or authors.endswith(".") else "."
    head = f"{authors}{stop} {title}" if authors else title
    return f"{head}, {tail}" if tail else head''',
'''def book_line(key: str) -> str:
    """`Kliegman R, ed. Nelson Textbook of Pediatrics. 22nd ed. Elsevier; 2024.`"""
    authors, title, edition, publisher, year = BOOKS[key]
    parts = []
    if authors:
        # A corporate author has no "eds." to end it, so it would otherwise run
        # straight into the title.
        parts.append(authors if authors.endswith(".") else f"{authors}.")
    parts.append(f"{title}.")
    if edition:
        parts.append(f"{edition}.")
    if publisher and year:
        parts.append(f"{publisher}; {year}.")
    elif publisher:
        parts.append(f"{publisher}.")
    elif year:
        parts.append(f"{year}.")
    return " ".join(parts)''')
open(p, 'w').write(s)
print('written')
