#!/usr/bin/env python3
"""Offline validation; standard library only. Run from anywhere."""
from pathlib import Path
from html.parser import HTMLParser
from urllib.parse import urlsplit,unquote
import json,hashlib,re
root=Path(__file__).resolve().parent
errors=[];checked=0
for name in ['ASSET-INDEX.json','RELEASE-MANIFEST.json']:
 data=json.loads((root/name).read_text())
 for entry in data['files']:
  path=root/entry['path'];checked+=1
  if not path.is_file():errors.append('Missing '+entry['path'])
  elif hashlib.sha256(path.read_bytes()).hexdigest()!=entry['sha256']:errors.append('Hash mismatch '+entry['path'])
class Links(HTMLParser):
 def __init__(self):super().__init__();self.links=[]
 def handle_starttag(self,tag,attrs):
  for k,v in attrs:
   if k in ['href','src'] and v:self.links.append(v)
for name in ['index.html','README.md','CHATGPT.md','TASK-BRIEFS.md','EXAMPLES.md']:
 path=root/name;s=path.read_text()
 if name.endswith('.html'):
  parser=Links();parser.feed(s);links=parser.links
 else:links=re.findall(r'\]\(([^)]+)\)',s)
 for link in links:
  u=urlsplit(link)
  if u.scheme or u.netloc or not u.path:continue
  p=(path.parent/unquote(u.path)).resolve()
  if not p.is_relative_to(root) or not p.exists():errors.append(name+' missing/escaping link '+link)
# Every catalogue record links directly to a real, indexed file.
for entry in json.loads((root/'ASSET-INDEX.json').read_text())['files']:
 if entry.get('public_web_subset') is False and json.loads((root/'PROVENANCE.json').read_text())['distribution']=='public-web':errors.append('Private file in public index '+entry['path'])
result={'ok':not errors,'hash_checks':checked,'errors':errors}
print(json.dumps(result,indent=2))
raise SystemExit(1 if errors else 0)
