#!/usr/bin/env python3
"""Validate after.html against the live page's form (stdlib only).
Usage: python3 check_after.py AFTER.html BEFORE.html [SITE_PUBLIC_DIR]"""
import os, re, sys
from html.parser import HTMLParser

VOID = {"area","base","br","col","embed","hr","img","input","link","meta","source","track","wbr"}
class P(HTMLParser):
    def __init__(self):
        super().__init__(); self.stack, self.errors = [], []
        self.ids, self.hrefs, self.scripts, self.form, self.fields = [], [], [], None, []
    def handle_starttag(self, t, a):
        a = dict(a)
        if t not in VOID: self.stack.append(t)
        if a.get("id"): self.ids.append(a["id"])
        if t == "a" and a.get("href"): self.hrefs.append(a["href"])
        if t == "script": self.scripts.append(a.get("src") or a.get("type", "inline"))
        if t == "form": self.form = (a.get("action"), a.get("method"))
        if t in ("input", "select", "textarea"): self.fields.append((a.get("name"), a.get("value") if a.get("type") == "hidden" else None))
    def handle_endtag(self, t):
        if t in VOID: return
        if self.stack and self.stack[-1] == t: self.stack.pop()
        else: self.errors.append(f"unexpected </{t}> (open: {self.stack[-3:]})")

def parse(path):
    p = P(); p.feed(open(path, encoding="utf-8").read()); p.close(); return p

after, before = sys.argv[1], sys.argv[2]
site = sys.argv[3] if len(sys.argv) > 3 else None
a, b = parse(after), parse(before)
raw = open(after, "rb").read(); txt = raw.decode()
ok = True
def check(name, cond, detail=""):
    global ok; ok &= bool(cond); print(f"[{'PASS' if cond else 'FAIL'}] {name}{': ' + detail if detail else ''}")

check("HTML parses with balanced tags", not a.errors and not a.stack, "; ".join(a.errors[:3]) or "0 errors")
dupes = sorted({i for i in a.ids if a.ids.count(i) > 1})
check("ids are unique", not dupes, f"{len(a.ids)} ids" + (f", dupes {dupes}" if dupes else ""))
anchors = [h for h in a.hrefs if h.startswith("#")]
missing = [h for h in anchors if h[1:] not in a.ids]
check("internal anchors resolve", not missing, f"{len(anchors)} anchors, {len(set(anchors))} unique, missing {missing}")
dashes = txt.count("\u2014") + txt.count("\u2013") + txt.count("&mdash;") + txt.count("&ndash;")
check("no em or en dashes", dashes == 0, f"{dashes} found")
ext = [s for s in a.scripts if s.startswith("http")]
check("no external scripts", not ext, f"scripts: {a.scripts}")
check("form action and method unchanged", a.form == b.form, f"{a.form}")
names = lambda p: [n for n, _ in p.fields]
check("same form field names, same order", names(a) == names(b), ", ".join(names(a)))
hidden_a = dict((n, v) for n, v in a.fields if v is not None)
hidden_b = dict((n, v) for n, v in b.fields if v is not None)
check("access key is the placeholder", hidden_a.get("access_key") == "YOUR_WEB3FORMS_KEY")
check("real key not copied", hidden_b.get("access_key") not in txt)
check("subject and from_name unchanged", all(hidden_a.get(k) == hidden_b.get(k) for k in ("subject", "from_name")), hidden_a.get("subject"))
check("viewport meta present", 'name="viewport"' in txt)
check("no placeholder text", not re.search(r"\bTBD\b|lorem|\[insert", txt, re.I))
if site:
    paths = sorted({h.split("#")[0] for h in a.hrefs if h.startswith("/")})
    for pth in paths:
        exists = os.path.exists(os.path.join(site, pth.strip("/"), "index.html"))
        print(f"[{'PASS' if exists else 'NOTE'}] site path {pth}: {'exists' if exists else 'not in site yet (created by the portfolio deploy)'}")
print(f"bytes: {len(raw):,}")
print("RESULT:", "ALL CHECKS PASS" if ok else "FAILURES ABOVE")
sys.exit(0 if ok else 1)
