#!python
# Copies the given input file, removing the parts specific to the Web,
# so it can be converted to an email
from datetime import date
from docutils.parsers.rst.directives.misc import Date
import subprocess

import argparse
import re
from pathlib import Path

from util import get_latest_newsletter_number

MAIL_GENERATOR = "/opt/homebrew/bin/mdtosendy"


# Find the number of the letter to create
letter_number = get_latest_newsletter_number()

source = Path(f"./content/newsletter/craft-letter-{letter_number}.md")

if not source.is_file():
    print(f"ERROR: file not found {source}")
    exit(1)

print(f"Processing {source}")

input = source.read_text()

regex = re.compile(r"Title.*svg\">", re.S)
output = re.sub(regex, "", input)
destination = Path.cwd() / "mail" / source.name

print(f"Writing {destination}")
destination.write_text(output)

subprocess.run([MAIL_GENERATOR, str(destination)])

generated_mail = Path("mail") / f"craft-letter-{letter_number}.html"
today = date.today()
mail_content = generated_mail.read_text()
mail_content = mail_content.replace("{{YEAR}}", str(today.year))
generated_mail.write_text(mail_content)

subprocess.run(["open", str(generated_mail)])
