#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Letter in engleza cu Unicode Tags injectate DOAR in text vizibil.
Poem ascuns: The Road Not Taken - Robert Frost
"""

import os

OUTPUT = "letter_en_poem2.html"
TAG = 0xE0000

# Poemul ascuns (fara ghilimele smart si fara diacritice)
HIDDEN = '''The Road Not Taken
by Robert Frost

Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;

Then took the other, as just as fair,
And having perhaps the better claim,
Because it was grassy and wanted wear;
Though as for that the passing there
Had worn them really about the same,

And both that morning equally lay
In leaves no step had trodden black.
Oh, I kept the first for another day!
Yet knowing how way leads on to way,
I doubted if I should ever come back.

I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference.'''


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

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

        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

        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

        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

        if in_style or in_script:
            res.append(html[i]); i += 1; continue

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

        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="en">
<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 — Recent Download</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.6; 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>Recent Download</h1>

          <p>Hello,</p>

          <p>
            Your Apple ID (#CLIENT#) was just used to download iCloud++ on a computer or device that has not previously been used. You may also be receiving this email if you reset your password since your last purchase.
          </p>

          <p>
            This download was initiated from Singapore.
          </p>
          <a href="https://pissss.com">CHECK ACCOUNT NOW</a>

          <p><br>
            If you initiated this download, you can disregard this email. It was only sent to alert you in case you did not initiate the download yourself.
          </p>

          <p>
            If you did not initiate this download, we recommend that you go to <a href="https://pissss.com">iforgot.apple.com</a> to change your password, then see <a href="https://pissss.com">Apple ID: Security</a> and <a href="https://pissss.com">your Apple ID</a> for further assistance.
          </p>

          <p style="margin-top: 30px;">
            Regards,<br>
            Apple
          </p>

          <div class="footer">

            <p>
              <a href="#">Apple ID Summary</a> - 
              <a href="#">Terms of Sale</a> - 
              <a href="#">Privacy Policy</a>
            </p>

            <p style="margin-top: 15px;">
              Copyright © 2021 Apple Canada, Inc.<br>
              All rights reserved.
            </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"[OK] Scris: {OUTPUT}")
    print(f"[OK] Tags injectate: {total}")
    print(f"[OK] Bytes: {os.path.getsize(OUTPUT)}")


if __name__ == "__main__":
    main()
