"""Public HTML and redirects, asset integrity, and edited inventory regressions.
Run with PHP 8.4 on PATH and Python 3 with lxml installed. Uses an isolated temporary SQLite file.
"""
import os,sys,pathlib,subprocess,tempfile,socket,ssl,base64,time,secrets,urllib.request,urllib.error,urllib.parse,xml.etree.ElementTree as ET,hashlib,json,collections,sqlite3
from lxml import html
root=pathlib.Path(__file__).resolve().parents[1];tmp=tempfile.TemporaryDirectory();work=pathlib.Path(tmp.name);db=work/'db.sqlite';store=work/'storage'
for p in ['logs','framework/views','framework/sessions','framework/cache/data','app/private/photos']:(store/p).mkdir(parents=True,exist_ok=True)
with socket.socket() as s:s.bind(('127.0.0.1',0));port=s.getsockname()[1]
url=f'http://127.0.0.1:{port}'
env={**os.environ,'APP_ENV':'testing','APP_URL':url,'APP_KEY':'base64:'+base64.b64encode(secrets.token_bytes(32)).decode(),'APP_DEBUG':'false','SESSION_SECURE_COOKIE':'false','SESSION_DRIVER':'file','CACHE_STORE':'file','DB_DATABASE':str(db),'DB_CONNECTION':'sqlite','LARAVEL_STORAGE_PATH':str(store)}
php='php';subprocess.run([php,'artisan','dealer:install'],cwd=root,env=env,check=True,stdout=subprocess.DEVNULL)
proc=subprocess.Popen([php,'-S',f'127.0.0.1:{port}','-t','public','tests/router.php'],cwd=root,env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
class NoRedirect(urllib.request.HTTPRedirectHandler):
 def redirect_request(self,*a):return None
op=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect)
def get(p,host='getanybus.com'):
 try:r=op.open(urllib.request.Request(url+p,headers={'Host':host}),timeout=20)
 except urllib.error.HTTPError as e:r=e
 with r:return r.status, r.headers, r.read()
def main():
 for _ in range(60):
  try:
   with socket.create_connection(('127.0.0.1',port),timeout=.5):break
  except OSError:time.sleep(.1)
 pages=json.loads((root/'resources/data/pages.json').read_bytes());smap=ET.fromstring(get('/sitemap.xml')[2]);urls={u.text.removeprefix('https://getanybus.com') for u in smap.findall('.//{*}loc')};assert set(pages)==urls,(len(urls),set(pages)-urls,urls-set(pages))
 print(f'{len(urls)} sitemap URLs match the shipped page map',flush=True)
 assets=set();linked=set()
 for p,f in pages.items():
  st,h,b=get(p); assert st==200 and b==(root/'resources/pages'/f).read_bytes(),(p,st,len(b));doc=html.fromstring(b)
  canon=doc.xpath('//link[@rel="canonical"]/@href'); assert canon==['https://getanybus.com'+p],(p,canon)
  for t in doc.xpath('//*[@src or @href]'):
   for attr in ('src','href'):
    target=t.get(attr)
    if not target:continue
    u=urllib.parse.urlparse(urllib.parse.urljoin('https://getanybus.com'+p,target)); 
    if u.hostname not in ('getanybus.com','www.getanybus.com') or u.scheme not in ('https','http'):continue
    if u.path.startswith(('/sales/','/staff/','/auth/','/api/')) and t.tag=='a': continue
    path=u.path
    if (root/'public'/path.lstrip('/')).is_file():assets.add(path)
    elif path not in pages and path not in ('/','/index.html'):linked.add(path)
 print(f'{len(pages)} bilingual page responses match the shipped templates byte for byte; each has its HTTPS canonical',flush=True)
 for p in sorted(assets):
  st,h,b=get(urllib.parse.quote(p,safe='/%'));assert st==200 and hashlib.sha256(b).digest()==hashlib.sha256((root/'public'/p.lstrip('/')).read_bytes()).digest(),(p,st)
 allstatic=[p for p in (root/'public').rglob('*') if p.is_file() and p.suffix.lower() in ('.jpg','.webp','.png','.gif','.jpeg','.pdf','.js','.css','.svg','.ico')]
 for f in allstatic:
  p='/'+f.relative_to(root/'public').as_posix()
  if p not in assets:
   st,h,b=get(urllib.parse.quote(p,safe='/%'));assert st==200 and b==f.read_bytes(),(p,st)
 print(f'{len(allstatic)} local photos, PDFs, styles and scripts served intact; {len(assets)} directly referenced in page markup',flush=True)
 extra={p:get(urllib.parse.quote(p,safe='/%'))[:2] for p in linked};print('Extra internal paths', {k:(v[0],v[1].get('Location','')) for k,v in extra.items()}, flush=True)
 red=json.loads((root/'resources/data/redirects.json').read_bytes()); red.update({'/SERVICE-AREA/Connecticut?utm_source=qa':'/service-areas/connecticut/?utm_source=qa','/sitemap_index.xml':'/sitemap.xml','/inventory/A5352':'/inventory/a5352/','/NEW-INVENTORY-DETAIL-PAGE/?Stock=5352':'/inventory/a5352/','/es/new-inventory-detail-page/?stock=a5352':'/es/inventory/a5352/','/new-inventory-detail-page/?vin='+json.loads((root/'resources/data/original.json').read_bytes())[0]['vin']:'/inventory/a5434/','/index.php?page_id=4209':'/ebizautos-slider/'})
 for hostname,should_index in [('getanybus.com',True),('preview.example.invalid',False)]:
  status,headers,robots=get('/robots.txt',hostname);assert status==200 and (b'Disallow: /\n' not in robots)==should_index
  status,headers,body=get('/',hostname);dom=html.fromstring(body);assert ('noindex' not in dom.xpath('//meta[@name="robots"]/@content')[0])==should_index and ('noindex' not in headers.get('X-Robots-Tag',''))==should_index
  assert dom.xpath('//link[@rel="canonical"]/@href')==['https://getanybus.com/']
 print('Production and alternate-host robots, indexing directives and production HTTPS canonicals verified',flush=True)
 for p,target in red.items():
  st,h,_=get(p);assert st==301 and h.get('Location')==url+target,(p,st,h.get('Location'),target)
 assert get('/pancakeswap-v3-farming-a-practical-guide-to-real-yield-on-bnb-chain/')[0]==410
 assert get('/new-inventory-detail-page/?stock=missing')[0]==302 and get('/inventory/missing/')[0]==404
 print(f'{len(red)} permanent redirect status codes and destinations, retired 410, unknown inventory 404 and temporary finder redirect verified',flush=True)


def check():
 for _ in range(60):
  try:
   with socket.create_connection(('127.0.0.1',port),timeout=.3):break
  except OSError:time.sleep(.1)
 def doc(p,st=200):
  code,h,b=get(p)
  if code>=500:
   print([z for f in (store/'logs').glob('*') for z in f.read_text().splitlines() if 'ERROR' in z][:1],flush=True)
  assert code==st,(p,code,b[:350]);return html.fromstring(b)
 bus=json.loads((root/'resources/data/original.json').read_bytes())[0]
 new={**bus,'stock':'QA204','title':'Testing New Shuttle','esTitle':'Autobús de prueba','description':'New description only.','descriptionEs':'Descripción nueva.','images':bus['images'][1:4],'price':12345,'inventoryType':'shuttle-van','video':None,'vin':'','nonCdl':True,'wheelchairPositions':97}
 dbh=sqlite3.connect(db)
 for stock,r in ((new['stock'],new),(bus['stock'],{**bus,'price':98765})):
  values=[stock,json.dumps(r),json.dumps(r),'active',1,'tester','2026-12-04'];dbh.execute('insert into bus_inventory(stock,draft,live,state,version,editor,updated) values(?,?,?,?,?,?,?)',values)
 dbh.commit()
 for es in (False,True):
  pref='/es' if es else '';url=f'{pref}/inventory/qa204/';d=doc(url);text=d.xpath('//main')[0].text_content()
  assert ('Autobús de prueba' if es else 'Testing New Shuttle') in text and ('Descripción nueva.' if es else 'New description only.') in text
  assert '$12,345' in text and 'A5352' not in html.tostring(d,encoding='unicode') and d.xpath('//img[@id="hero-photo"]/@src')==[new['images'][0]]
  schema=json.loads(d.xpath('//script[@type="application/ld+json"]/text()')[0]);assert schema['sku']=='QA204' and schema['offers']['price']==12345 and schema['mileageFromOdometer']['value']==int(bus['miles'].replace(',','')) and schema['offers']['seller']['@id'].endswith('/#dealership')
  assert d.xpath('//a[@data-chrome-language]/@href')==[('/inventory/qa204/' if es else '/es/inventory/qa204/')]*2
  home=doc('/?lang=es' if es else '/');cat=json.loads(home.xpath('//script[@id="homeCatalog"]/text()')[0]);newrow=next(v for v in cat['active'] if v['stock']=='QA204');assert newrow['vehicleType']=='shuttle-van' and 'transit vans' in newrow['typeSearch'] and newrow['photos']==3
  search=doc(f'{pref}/inventory-of-used-buses-and-vans/wheelchair-bus-and-wheelchair-vans/?positions=97');zone=search.xpath('//section[@class="wheelchair-inventory"]')[0];assert len(zone.xpath('.//article'))==1 and 'QA204' in zone.text_content() and ': 1' in zone.text_content() and zone.xpath('.//select[@name="positions"]/option[@selected]/text()')==['97']
  none=doc(f'{pref}/inventory-of-used-buses-and-vans/wheelchair-bus-and-wheelchair-vans/?seats=999999');zone=none.xpath('//section[@class="wheelchair-inventory"]')[0];assert not zone.xpath('.//article') and ': 0' in zone.text_content()
  mini=doc(f'{pref}/buses/mini-buses/');assert mini.xpath('//main/h1')
 print('PASS new and edited listing SEO, stock, image order/count, translations, price, filter catalog, category and accessible inventory filters in both languages',flush=True)
 slug='/blog/check-new-article-qa/';post={'id':'qa','title':'QA New Article','summary':'A new summary','body':'Article with <script>plain</script> text.','cat':'buying','path':slug,'date':'2026-12-04'};raw=json.dumps(post);dbh.execute("insert into blog_posts(id,draft,published,version,editor,updated) values(?,?,?,1,'tester','2026-12-04')",('qa',raw,raw));dbh.commit()
 for pref in ('','/es'):
  d=doc(pref+slug);assert 'QA New Article' in d.xpath('//main/h1/text() | //main//h1/text()') and not d.xpath('//div[@class="article-copy"]//script')
  assert d.xpath('//link[@rel="canonical"]/@href')==['https://getanybus.com'+slug] and not d.xpath('//link[@hreflang]'); assert d.xpath('//a[@data-chrome-language]/@href')==[('' if pref else '/es')+slug]*2
  search=doc(pref+'/blog/?q=QA%20New');assert len(search.xpath('//article[@class="topic-card"]'))==1
 print('PASS new published article, search results, actual-language canonical and markup escaping',flush=True)
 dbh.execute("update bus_inventory set state='sold' where stock='QA204'");dbh.commit()
 assert 'QA204' in doc('/sold-buses/').xpath('//div[@class="archive-grid"]')[0].text_content()
 assert 'QA204' not in doc('/inventory-of-used-buses-and-vans/wheelchair-bus-and-wheelchair-vans/').xpath('//section[@class="wheelchair-inventory"]')[0].text_content()
 smap=lambda: {u.text.removeprefix('https://getanybus.com') for u in ET.fromstring(get('/sitemap.xml')[2]).findall('.//{*}loc')}
 assert {'/inventory/qa204/','/es/inventory/qa204/',slug}<=smap() and '/es'+slug not in smap()
 dbh.execute("update bus_inventory set state='trash-sold' where stock='QA204'");dbh.commit()
 assert get('/inventory/qa204/')[0]==404 and '/inventory/qa204/' not in smap() and '/es/inventory/qa204/' not in smap()
 print('PASS sold and trash transitions update directories, English/Spanish sitemap URLs, 404 on archived draft removal',flush=True)
 defaults=json.loads((root/'resources/data/galleryDefaults.json').read_bytes())
 photos=defaults['hero']+[dict(defaults['resources'][0],title='Alternate hero')]
 dbh.execute("insert into site_photo_galleries(area,items,version,edition) values('hero',?,1,63)",(json.dumps(photos),));dbh.commit()
 for p in ['/','/?lang=es']:
  d=doc(p);assert len(d.xpath('//div[@class="homepage-photos"]//button[@data-home-photo]'))==len(photos)
 print('PASS edited two-photo home gallery in both languages, stage and controls in the same gallery',flush=True)
 guides=json.loads((root/'resources/data/guideReviews.json').read_bytes());guide=next(k for k,v in guides.items() if v['es'])
 for lang,prefix in [('en',''),('es','/es')]:
  dbh.execute('insert into editorial_reviews(path,language,digest,reviewed_at) values(?,?,?,?)',(guide,lang,guides[guide][lang],'2026-10-01T00:00:00.000Z'))
 dbh.commit()
 for prefix in ('','/es'):
  d=doc(prefix+guide);assert 'Charles Kaufman' in ' '.join(d.xpath('//article//p[@class="byline"]//text()'))
 fingerprint=lambda values:hashlib.sha256(json.dumps(values,ensure_ascii=False,separators=(',',':')).encode()).hexdigest()
 dbh.execute('insert into editorial_reviews(path,language,digest,reviewed_at) values(?,?,?,?)',(slug,'en',fingerprint([post['title'],post['summary'],post['body'],post['date']]),'2026-10-01T00:00:00.000Z'));dbh.commit()
 assert 'Charles Kaufman' in ' '.join(doc(slug).xpath('//article//p[@class="byline"]//text()'))
 post['summary']='New summary since review';dbh.execute('update blog_posts set draft=?, published=?,version=2 where id=?',(json.dumps(post),json.dumps(post),'qa'));dbh.commit()
 assert 'Charles Kaufman' not in ' '.join(doc(slug).xpath('//article//p[@class="byline"]//text()'))
 print('PASS bilingual guide and article owner-review confirmations carry through and a published summary edit expires the previous confirmation',flush=True)
 dbh.close()
try:
 main()
 check()
finally:proc.terminate();proc.wait();tmp.cleanup()
