"""TechsNuggets portable file audit. Run: python3 check-static-site.py /path/to/public_html
Standard library only. Does not fetch pages, submit forms, render CSS or execute browser scripts.
"""
from pathlib import Path
from html.parser import HTMLParser
from urllib.parse import urlsplit, unquote
from collections import Counter
import xml.etree.ElementTree as ET
import json, sys
class Page(HTMLParser):
    def __init__(self, source):
        super().__init__(convert_charrefs=True)
        self.ids=[];self.refs=[];self.h1=0;self.noindex=False
        self.feed(source)
    def handle_starttag(self,tag,attrs):
        a=dict(attrs)
        if 'id' in a:self.ids.append(a['id'])
        if tag=='h1':self.h1+=1
        if tag=='meta' and a.get('name','').lower()=='robots':
            self.noindex='noindex' in a.get('content','').lower()
        for key in ['href','src']:
            if a.get(key):self.refs.append(a[key])
root=Path(sys.argv[1]).resolve()
pages={p.resolve():Page(p.read_text()) for p in root.rglob('*.html')}
issues=[];checked=0
for p,d in pages.items():
    name=str(p.relative_to(root))
    if not p.name.startswith('google') and d.h1!=1:issues.append([name,'h1 count',d.h1])
    for ident,count in Counter(d.ids).items():
        if count>1:issues.append([name,'duplicate ID',ident])
    for ref in d.refs:
        u=urlsplit(ref)
        if u.scheme or u.netloc:continue
        checked+=1
        dest=((root/u.path.lstrip('/')) if u.path.startswith('/') else (p.parent/u.path)) if u.path else p
        dest=dest.resolve()
        if not dest.is_relative_to(root):issues.append([name,'outside root',ref]);continue
        if dest.is_dir():dest=dest/'index.html'
        if not dest.exists():issues.append([name,'missing file',ref]);continue
        if u.fragment and dest in pages and unquote(u.fragment) not in pages[dest].ids:
            issues.append([name,'missing fragment',ref])
ns={'s':'http://www.sitemaps.org/schemas/sitemap/0.9'}
locs=ET.parse(root/'sitemap.xml').findall('.//s:loc',ns)
for loc in locs:
    path=urlsplit(loc.text).path.lstrip('/') or 'index.html'
    dest=(root/path).resolve()
    if dest not in pages:issues.append(['sitemap','missing page',path])
    elif pages[dest].noindex:issues.append(['sitemap','noindex page',path])
print(json.dumps({'scope':'Local HTML references, IDs, main-heading counts and sitemap/indexing consistency only',
    'htmlPages':len(pages),'localReferencesChecked':checked,'sitemapEntries':len(locs),
    'issues':issues,'notTested':['Rendering/mobile interaction','HTTP responses and redirects','Mail delivery','Page speed','External links']},indent=2))
sys.exit(1 if issues else 0)
