from html.parser import HTMLParser
from pathlib import Path
import subprocess,sys,json,xml.etree.ElementTree as ET
php=sys.argv[1]
class Page(HTMLParser):
 def __init__(self):super().__init__();self.h1=0;self.title=0;self.canonical=[];self.description=[];self.links=[];self.scripts=[];self.in_ld=False;self.ld=''
 def handle_starttag(self,t,a):
  d=dict(a)
  if t=='h1':self.h1+=1
  if t=='title':self.title+=1
  if t=='link' and d.get('rel')=='canonical':self.canonical.append(d['href'])
  if t=='meta' and d.get('name')=='description':self.description.append(d['content'])
  if t=='a':self.links.append(d.get('href',''))
  if t=='script' and d.get('type')=='application/ld+json':self.in_ld=True
  if t=='script' and 'src'in d:self.scripts.append(d['src'])
 def handle_endtag(self,t):
  if t=='script':self.in_ld=False
 def handle_data(self,d):
  if self.in_ld:self.ld+=d
paths=['/','/hosting','/about','/contact','/knowledge']
paths+=['/solutions/'+s for s in json.load(open('app/solutions.json'))]
paths+=['/plans/'+p['id'] for p in json.load(open('app/catalog.json'))]
paths+=['/knowledge/'+p['slug'] for p in json.load(open('app/knowledge.json'))]
for path in paths:
 raw=subprocess.check_output([php,'tests/render-public.php',path],text=True);p=Page();p.feed(raw)
 assert p.h1==1,(path,'H1 count',p.h1)
 assert p.title==1 and p.description and p.canonical==['https://hostical.net'+path],path
 assert json.loads(p.ld)['@context']=='https://schema.org'
 assert not any('/assets/app.' in script for script in p.scripts),'Dashboard bundle loaded on public page'
 assert not any('href=""' in raw for _ in [0]),path
 sitemap=subprocess.check_output([php,'tests/render-public.php','/sitemap.xml'],text=True) if path=='/' else None
 if sitemap: assert len(ET.fromstring(sitemap))==len(paths)
notfound=subprocess.check_output([php,'tests/render-public.php','/missing'],text=True)
assert 'That page is off the grid' in notfound and 'noindex,follow' in notfound
print('PASS:',len(paths),'server-rendered pages: metadata, canonical, H1, schema, lightweight JS; sitemap and missing-page content.')
