"""Troca yii\\swiftmailer\\Mailer por yii\\symfonymailer\\Mailer em config/web.php e config/console.php (bytes preservados)."""
import re
from pathlib import Path

RAIZ = Path(__file__).resolve().parents[2]
BS = chr(92)

for rel in ("config/web.php", "config/console.php"):
    p = RAIZ / rel
    s = p.read_bytes().decode("latin-1")
    nl = "\r\n" if "\r\n" in s else "\n"
    classe_antiga = "'yii" + BS + "swiftmailer" + BS + "Mailer'"
    ini = s.index("'mailer' => [")
    assert s.index(classe_antiga, ini) - ini < 80, rel
    j = s.index("'transport' => [", ini)
    fim_transport = s.index("],", j) + 2
    fim = s.index("],", fim_transport) + 2
    bloco = s[ini:fim]
    recuo = re.search(r"\n([ \t]*)'class'", bloco).group(1)
    senha = re.search(r"'password' => ([^,\n]+),", bloco).group(1)
    i2 = recuo + "    "
    novo = (
        "'mailer' => [" + nl
        + recuo + "// SwiftMailer (abandonado) usa callable obsoleto no PHP 8.2; symfony/mailer tem a mesma API do Yii" + nl
        + recuo + "'class' => " + BS + "yii" + BS + "symfonymailer" + BS + "Mailer::class," + nl
        + recuo + "'transport' => [" + nl
        + i2 + "'scheme' => 'smtp', // porta 587 com STARTTLS (antes: encryption tls)" + nl
        + i2 + "'host' => 'smtp.sendgrid.net'," + nl
        + i2 + "'username' => 'apikey'," + nl
        + i2 + "'password' => " + senha + "," + nl
        + i2 + "'port' => 587," + nl
        + recuo + "]," + nl
        + recuo[:-4] + "],"
    )
    p.write_bytes((s[:ini] + novo + s[fim:]).encode("latin-1"))
    print(rel, "ok")
