import hashlib,json,pathlib,re,sys
from urllib.parse import parse_qs,urlsplit
source,target=map(pathlib.Path,sys.argv[1:]);original=source.read_bytes();urls=json.loads(original)
if not isinstance(urls,list) or not 1<=len(urls)<=200:raise ValueError('Provide 1..200 public article URLs')
rows=[];groups={}
for url in urls:
if not isinstance(url,str) or not url or any(c.isspace() or ord(c)<32 or ord(c)==127 for c in url):raise ValueError('Use an intact public URL without whitespace/control characters')
parsed=urlsplit(url)
if parsed.scheme not in ('http','https') or parsed.hostname!='mp.weixin.qq.com' or parsed.username is not None or parsed.password is not None or parsed.port not in (None,80,443):raise ValueError('Expected a WeChat article host without embedded credentials')
query=parse_qs(parsed.query,keep_blank_values=True)
if any(k.startswith('amp;') for k in query):raise ValueError('Copy the actual URL, not HTML-escaped markup')
if any(k.lower() in ('pass_ticket','key','uin','ticket','access_token') for k in query):raise ValueError('Use a public share URL without browser-session parameters')
for key in ['__biz','mid','idx','sn']:
if key in query and (len(query[key])!=1 or not query[key][0] or any(c.isspace() or ord(c)<32 or ord(c)==127 for c in query[key][0])):raise ValueError('Ambiguous, blank or malformed article component: '+key)
if parsed.path=='/s':
if not all(k in query for k in ['__biz','mid','idx']):raise ValueError('Long-link identity needs __biz, mid and idx')
biz,mid,idx=(query[k][0] for k in ['__biz','mid','idx'])
if not re.fullmatch(r'[0-9]+',mid) or int(mid)<1 or not re.fullmatch(r'[0-9]+',idx) or int(idx)<1:raise ValueError('mid/idx must be original positive ASCII digit strings')
identity=[biz,mid,idx]
row={'url':url,'kind':'long','biz':biz,'mid':mid,'idx':idx,'sn_present':'sn' in query,'identity':identity,
'position':'headline' if int(idx)==1 else 'secondary'}
groups.setdefault(json.dumps(identity,ensure_ascii=False),[]).append(len(rows))
elif parsed.path.startswith('/s/') and parsed.path[3:] and '/' not in parsed.path[3:]:
row={'url':url,'kind':'short','biz':None,'mid':None,'idx':None,'sn_present':'sn' in query,'identity':None,'position':'not_derived_from_short_link'}
else:raise ValueError('Expected /s with long parameters or one /s/ article token')
rows.append(row)
target.mkdir()
(target/'input-urls.json').write_bytes(original)
(target/'link-audit.json').write_text(json.dumps({'links':rows,
'same_long_identity_groups':[{'identity':json.loads(k),'input_indices':v} for k,v in groups.items() if len(v)>1],
'input_sha256':hashlib.sha256(original).hexdigest(),'short_long_aliases_resolved':False,
'network_requests':0,'article_availability_verified':False},ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps({'links':len(rows),'long_links':sum(r['kind']=='long' for r in rows),'short_links':sum(r['kind']=='short' for r in rows),'network_requests':0}))