#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Injecteaza poezia in letterul chinezesc (Unicode Tags dupa fiecare cuvant ASCII).
"""

import os

INPUT  = "letter_cn.html"           # letterul chinezesc salvat
OUTPUT = "letter_cn_poem.html"
TAG = 0xE0000

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)


def main():
    if not os.path.isfile(INPUT):
        print(f"[!] Nu gasesc {INPUT}")
        return

    with open(INPUT, "r", encoding="utf-8") as f:
        html = f.read()

    result = inject_after_words(html, 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()
