#!/usr/bin/env python3
"""Check what a saved (or translated) webpage copy still depends on and what it left in the source language.

Usage:
    python3 page_copy_check.py page.html
    python3 page_copy_check.py original.html translated.html

Part 1 lists what the copy still loads from the web: a <base> address,
scripts, stylesheets and images. A copy that points at the original site
looks right only while that site keeps serving those files, and scripts can
redraw the page in the original language when the file is opened.

Part 2 counts text that sits outside the page's normal reading text: the
<title>, meta description, image alt text, title / aria-label / placeholder
attributes, and code or pre blocks. With two files it also counts how many of
those items appear unchanged in the translated copy. An unchanged item usually
means the translator skipped it, though names, numbers and code can be the
same on purpose.

Standard library only (Python 3.8+). It reads local files; it never fetches a URL.
"""
import sys
from html.parser import HTMLParser

SKIP = {"script", "style", "noscript", "template"}
TEXT_KEYS = ("title", "meta description", "alt", "title attr", "aria-label", "placeholder", "code/pre")


def is_remote(url):
    url = (url or "").strip().lower()
    return url.startswith(("http://", "https://", "//"))


class Collector(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.items = {k: [] for k in TEXT_KEYS}
        self.deps = {"scripts": 0, "stylesheets": 0, "images": 0, "remote images": 0}
        self.base = None
        self.lang = None
        self.title_buf = None
        self.code_buf = None
        self.code_depth = 0
        self.skip_depth = 0
        self.body_chars = 0

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "html":
            self.lang = a.get("lang")
        if tag == "base" and self.base is None:
            self.base = a.get("href")
        if tag == "script":
            self.deps["scripts"] += 1
        if tag == "link" and "stylesheet" in (a.get("rel") or "").lower():
            self.deps["stylesheets"] += 1
        if tag == "img":
            self.deps["images"] += 1
            src = a.get("src") or ""
            if is_remote(src) or (self.base and not src.startswith("data:")):
                self.deps["remote images"] += 1
            self._add("alt", a.get("alt"))
        if tag in SKIP:
            self.skip_depth += 1
        if tag == "title" and self.title_buf is None:
            self.title_buf = []
        if tag in ("code", "pre"):
            if self.code_depth == 0:
                self.code_buf = []
            self.code_depth += 1
        if tag == "meta" and (a.get("name") or "").lower() == "description":
            self._add("meta description", a.get("content"))
        if tag != "title" and "title" in a:
            self._add("title attr", a.get("title"))
        for name in ("aria-label", "placeholder"):
            if name in a:
                self._add(name, a.get(name))

    def handle_endtag(self, tag):
        if tag in SKIP and self.skip_depth:
            self.skip_depth -= 1
        if tag == "title" and isinstance(self.title_buf, list):
            self._add("title", "".join(self.title_buf))
            self.title_buf = False
        if tag in ("code", "pre") and self.code_depth:
            self.code_depth -= 1
            if self.code_depth == 0:
                self._add("code/pre", "".join(self.code_buf))
                self.code_buf = None

    def handle_data(self, data):
        if isinstance(self.title_buf, list):
            self.title_buf.append(data)
        elif self.code_depth:
            self.code_buf.append(data)
        elif not self.skip_depth:
            self.body_chars += len(data.strip())

    def _add(self, key, value):
        value = " ".join((value or "").split())
        if value:
            self.items[key].append(value)


def collect(path):
    with open(path, encoding="utf-8", errors="replace") as f:
        c = Collector()
        c.feed(f.read())
    return c


def main(argv):
    if len(argv) not in (2, 3):
        print(__doc__.strip())
        return 2
    page = collect(argv[-1])
    src = collect(argv[1])
    print(f"Part 1: what {argv[-1]} still loads from the web")
    print(f"  <base href>: {page.base or 'none'}")
    for key, n in page.deps.items():
        print(f"  {key:<14}{n:>7}")
    print()
    print("Part 2: text outside the normal reading text")
    print(f"  html lang: {src.lang!r}" + (f" -> {page.lang!r}" if len(argv) == 3 else ""))
    print(f"  reading text characters: {src.body_chars}")
    header = f"  {'item':<18}{'count':>7}{'chars':>9}"
    if len(argv) == 3:
        header += f"{'unchanged in copy':>20}"
    print(header)
    for key in TEXT_KEYS:
        values = src.items[key]
        row = f"  {key:<18}{len(values):>7}{sum(len(v) for v in values):>9}"
        if len(argv) == 3:
            unchanged = set(page.items[key])
            row += f"{sum(v in unchanged for v in values):>20}"
        print(row)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
