"""Acquire only CC0 Quaternius sources into the isolated work directory."""
from pathlib import Path
import requests,json,hashlib,shutil,concurrent.futures
from html.parser import HTMLParser
class Rows(HTMLParser):
 def __init__(self,text):
  super().__init__();self.rows=[];self.current=None;self.feed(text)
 def handle_starttag(self,tag,attrs):
  a=dict(attrs)
  if a.get("role")=="row" and "data-id" in a:
   self.current=[a["data-id"],""];self.rows.append(self.current)
 def handle_data(self,data):
  if self.current is not None:self.current[1]+=" "+data
P=Path('/opt/creature-lib-20261017'); S=P/'sources'; evidence=[]
def fetch(url,path):
 r=requests.get(url,timeout=90);r.raise_for_status();path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(r.content)
 return r
for pack in ['ultimateanimatedanimals','ultimatemonsters']:
 fetch('https://quaternius.com/packs/'+pack+'.html',S/(pack+'-licence.html'))
r=requests.get('https://drive.google.com/drive/folders/1yJXdB1iSrI8Db7hG77zxZ66vKsqIt0ry',timeout=60)
s=Rows(r.text);items=[]
for fid,text in s.rows:
 import re
 m=re.search(r'([\w -]+\.(?:gltf|bin|png))',text)
 if m:
  name=m.group(1).strip();name=re.sub(r'^(?:Image|Text|Unknown) ','',name)
  items.append((name,fid))
print('ANIMAL FILES',items,flush=True)
def download(item):
 name,fid=item;p=S/'animals'/name;u='https://drive.google.com/uc?export=download&id='+fid
 if not p.exists():fetch(u,p)
 if p.suffix=='.gltf':
  try:json.loads(p.read_text())
  except ValueError:
   print("FAILED DOWNLOAD",name,flush=True);return {"failed":name,"url":u}
 return {'path':str(p.relative_to(P)),'url':u,'author':'Quaternius','licence':'CC0-1.0','pack_url':'https://quaternius.com/packs/ultimateanimatedanimals.html','sha256':hashlib.sha256(p.read_bytes()).hexdigest()}
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex:evidence.extend(ex.map(download,items))
fetch('https://drive.google.com/uc?export=download&id=1F2uy8T2fRpdc6gZ4mnS02_C2E63WvKtn',S/'animals/License.txt')
old=Path('/srv/archive/from-ax42-2026-09-30/local-forge-build-pre-0922/tideglass-asset-import-20260914')
records=json.loads((old/'evidence/quaternius-downloads.json').read_text())
for group,name in [('Big',n) for n in ['Orc','Yeti','Dino','Frog','MushroomKing','Cactoro','Fish','Alien','BlueDemon']]+[('Flying',n) for n in ['Goleling_Evolved','Dragon_Evolved','Armabee_Evolved','Pigeon','Squidle']]:
 src=old/'sources/quaternius'/group/(name+'.gltf');dst=S/'monsters'/group/src.name;dst.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(src,dst)
 atlas=src.parent/'Atlas_Monsters.png'
 if atlas.exists():shutil.copy2(atlas,dst.parent/atlas.name)
 rec=next(r for r in records if r['name']==src.name and r['group']==group)
 evidence.append({'path':str(dst.relative_to(P)),'url':'https://drive.google.com/uc?export=download&id='+rec['id'],'author':'Quaternius','licence':'CC0-1.0','pack_url':'https://quaternius.com/packs/ultimatemonsters.html','sha256':hashlib.sha256(dst.read_bytes()).hexdigest()})
shutil.copy2(old/'sources/quaternius/License.txt',S/'monsters/License.txt')
(P/'evidence/sources.json').write_text(json.dumps(evidence,indent=2))
for r in evidence:
 if 'path' not in r:continue
 p=P/r['path']
 if p.suffix=='.gltf':
  g=json.loads(p.read_text());print(p.name,'clips:',[a['name'] for a in g.get('animations',[])], 'triangles',sum(g['accessors'][pr['indices']]['count']//3 for m in g['meshes'] for pr in m['primitives']),flush=True)
