#!/usr/bin/env python3
"""Measure conversion and speed signals in a static HTML page (stdlib only).
Usage: python3 page_audit.py PAGE.html [PAGE2.html ...]"""
import gzip, re, sys
from html.parser import HTMLParser

class Audit(HTMLParser):
    def __init__(self):
        super().__init__()
        self.ext, self.links, self.ids, self.fields = [], [], set(), []
        self.reveal = 0; self.count0 = 0; self._tag = None
    def handle_starttag(self, tag, attrs):
        a = dict(attrs); self._tag = tag
        if a.get("id"): self.ids.add(a["id"])
        if "reveal" in (a.get("class") or "").split(): self.reveal += 1
        if "count" in (a.get("class") or "").split(): self.count0 += 1
        src = a.get("src") or (a.get("href") if tag == "link" else None)
        if src and src.startswith("http") and tag in ("script", "link", "img", "iframe"):
            if a.get("rel") not in ("canonical", "preconnect"):
                self.ext.append(f"{tag}: {src.split('?')[0]}")
        if tag == "a" and a.get("href"): self.links.append(a["href"])
        if tag in ("input", "select", "textarea") and a.get("type") not in ("hidden", "checkbox"):
            self.fields.append(a.get("name"))

def text_of(html):
    html = re.sub(r"<(script|style)\b.*?</\1>", " ", html, flags=re.S | re.I)
    return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html))

for path in sys.argv[1:]:
    raw = open(path, "rb").read(); html = raw.decode("utf-8")
    p = Audit(); p.feed(html)
    css = sum(len(m.encode()) for m in re.findall(r"<style\b.*?</style>", html, re.S))
    js = sum(len(m.encode()) for m in re.findall(r"<script\b(?![^>]*ld\+json).*?</script>", html, re.S))
    ld = sum(len(m.encode()) for m in re.findall(r"<script[^>]*ld\+json.*?</script>", html, re.S))
    words = re.findall(r"[A-Za-z']+", text_of(html))
    low = [w.lower() for w in words]
    cta = [l for l in p.links if "calendly" in l or l in ("#contact", "/#contact") or "onrender" in l]
    cta = [re.sub(r"^(https://calendly\.com)/[^/]+", r"\1/(handle)", l) for l in cta]
    print(f"== {path}")
    print(f"bytes: {len(raw):,} | gzip: {len(gzip.compress(raw)):,} | inline CSS: {css:,} | inline JS: {js:,} | JSON-LD: {ld:,}")
    print(f"external requests in HTML: {len(p.ext)}")
    for e in p.ext: print(f"  - {e}")
    print(f"visible words: {len(words)} | we/our/us: {sum(low.count(w) for w in ('we','our','us'))} | I/my/me: {sum(w in ('i','my','me') for w in low)}")
    print(f"links to a conversion target (form, booking, chat): {len(cta)} -> {sorted(set(cta))}")
    print(f"elements hidden until JS runs (.reveal): {p.reveal} | count-up stats starting at 0: {p.count0}")
    print(f"visible form fields: {p.fields}")
    print(f"em/en dashes in page: {html.count(chr(8212)) + html.count(chr(8211)) + html.count('&#8212;') + html.count('&mdash;')}")
