#!/usr/bin/env python3
"""Offline RaceSide release or production-pack verification; Python standard library only."""
from pathlib import Path
from html.parser import HTMLParser
from urllib.parse import urlsplit,unquote
import hashlib,json,re,struct,xml.etree.ElementTree as ET
root=Path(__file__).resolve().parent
errors=[];checked=0;links_checked=0
def fail(s):errors.append(s)
def local(relative):
 p=(root/relative).resolve()
 if not p.is_relative_to(root):raise ValueError('Path escapes release: '+relative)
 return p
manifest='RELEASE-MANIFEST.json' if (root/'RELEASE-MANIFEST.json').exists() else 'PACK-MANIFEST.json'
for name in ['ASSET-INDEX.json',manifest]:
 data=json.loads((root/name).read_text());seen=set()
 for item in data['files']:
  ref=item['path']
  if ref in seen:fail('Duplicate '+ref)
  seen.add(ref)
  try:p=local(ref)
  except ValueError as e:fail(str(e));continue
  checked+=1
  if not p.is_file():fail('Missing '+ref);continue
  if hashlib.sha256(p.read_bytes()).hexdigest()!=item['sha256']:fail('Hash mismatch '+ref)
  if item.get('bytes') is not None and p.stat().st_size!=item['bytes']:fail('Size mismatch '+ref)
assets=json.loads((root/'ASSET-INDEX.json').read_text())['files']
for a in assets:
 p=local(a['path'])
 if not p.exists():continue
 if not a.get('public_web_subset'):fail('Nonpublic asset '+a['path'])
 if p.suffix=='.png':
  raw=p.read_bytes()
  if raw[:8]!=b'\x89PNG\r\n\x1a\n':fail('Invalid PNG '+a['path']);continue
  w,h=struct.unpack('>II',raw[16:24]);d=a.get('dimensions') or {}
  if w!=d.get('width') or h!=d.get('height'):fail('PNG dimensions '+a['path'])
 if a['path'].startswith('Logos/') and p.suffix=='.svg':
  tree=ET.parse(p).getroot()
  if any(e.tag.split('}')[-1] in ['text','image','script','foreignObject'] for e in tree.iter()):fail('Unexpected SVG content '+a['path'])
  if not tree.get('viewBox'):fail('Missing viewBox '+a['path'])
  ids={e.get('id') for e in tree.iter() if e.get('id')}
  for e in tree.iter():
   for v in e.attrib.values():
    for ref in re.findall(r'url\(#([^)]+)\)',v):
     if ref not in ids:fail('Broken SVG reference '+ref+' in '+a['path'])
class Links(HTMLParser):
 def __init__(self):super().__init__();self.refs=[]
 def handle_starttag(self,t,attrs):
  self.refs.extend(v for k,v in attrs if k in ['src','href'] and v)
for p in root.glob('*'):
 if p.suffix not in ['.html','.md','.css']:continue
 s=p.read_text()
 if p.suffix=='.html':
  h=Links();h.feed(s);refs=h.refs
 elif p.suffix=='.css':refs=re.findall(r'url\([\'"]?([^\'")]+)',s)
 else:refs=re.findall(r'\]\(([^)]+)\)',s)
 for ref in refs:
  u=urlsplit(ref)
  if u.scheme or u.netloc or not u.path:continue
  # Explicit site navigation/history routes are outside a portable release.
  if u.path=='/' or u.path.startswith('/brand/releases/v1.1'):continue
  links_checked+=1
  try:target=local(unquote(u.path))
  except ValueError as e:fail(str(e));continue
  if not target.exists():fail(p.name+' missing link '+ref)
for p in root.rglob('*'):
 if p.is_file() and (p.suffix in ['.vectorcraft','.pem','.key'] or '.icon' in p.parts or p.name.startswith('.env')):fail('Private source in public distribution '+str(p.relative_to(root)))
print(json.dumps({'ok':not errors,'hash_checks':checked,'asset_records':len(assets),'links_checked':links_checked,'manifest':manifest,'errors':errors},indent=2))
raise SystemExit(bool(errors))

