#!/usr/bin/env python3
"""Kiểm tra inc/real-products/*.json (5 SP / danh mục). Chạy: python3 validate.py [key...]"""
import json,sys,os,re,glob
here=os.path.dirname(os.path.abspath(__file__))
cats=json.load(open('/tmp/claude-0/-home-claude-dev-pctech-com-vn/9f4ddf69-7e84-5f0a-b3fb-29b8dcc6c120/scratchpad/real_cats.json'))
keys=sys.argv[1:] or sorted(cats)
bad=0
for k in keys:
    p=os.path.join(here,k+'.json')
    if not os.path.exists(p): print(k,'THIẾU FILE'); bad+=1; continue
    try: d=json.load(open(p))
    except Exception as e: print(k,'JSON lỗi',e); bad+=1; continue
    errs=[]
    if not isinstance(d,list) or len(d)!=5: errs.append('cần đúng 5 mục')
    names=set(x[1].lower() for x in cats[k]['existing'])
    seen=set()
    for i,x in enumerate(d if isinstance(d,list) else []):
        t=f'#{i+1}'
        for f in ('brand','name','price','months','specs','source'):
            if f not in x: errs.append(t+' thiếu '+f)
        if errs and errs[-1].startswith(t): continue
        if x['name'].lower() in names or x['name'].lower() in seen: errs.append(t+' trùng tên')
        seen.add(x['name'].lower())
        if '[MẪU]' in x['name'] or 'mẫu' in x['name'].lower(): errs.append(t+' tên có chữ mẫu')
        if not isinstance(x['price'],int) or not (50000<=x['price']<=400000000): errs.append(t+' giá lạ')
        if not isinstance(x['months'],int) or not (0<=x['months']<=120): errs.append(t+' bảo hành lạ')
        if not isinstance(x['specs'],list) or len(x['specs'])<5 or any((not isinstance(s,list) or len(s)!=2 or not s[0] or not s[1]) for s in x['specs']): errs.append(t+' specs cần ≥5 cặp [nhãn,giá trị]')
        if not str(x['source']).startswith('http'): errs.append(t+' source phải là URL')
        if x['brand'].lower() not in x['name'].lower() and x['brand']!='PCTech': errs.append(t+' tên nên chứa tên hãng')
    print(k,'OK' if not errs else 'LỖI: '+'; '.join(errs)); bad+=bool(errs)
sys.exit(1 if bad else 0)
