"""Validator for the Launchpad SEO pack zip. Stdlib only: copy this one file anywhere and run
    python seopack_validate.py pack.zip
It checks the zip a research model (for example ChatGPT) returns before a builder agent turns it into pages.
Exit code 0 means the pack is safe to implement, 1 means fix the listed problems first."""
import io
import json
import re
import sys
import zipfile

VERSION = 1
REQUIRED = ('manifest.json', 'brand.json', 'sources.csv', 'llms.txt', 'README_IMPORT.md')
FAMILIES = ('free_tool', 'data', 'howto', 'compare', 'audience', 'platform', 'locale', 'research', 'glossary', 'faq', 'usecase', 'integration')
DASH = re.compile('[–—]')
FAKE = re.compile(r'\b(guarantee[sd]?|#1|number one|best in the world|100% (safe|accurate)|revolutionary|game.?chang)', re.I)
STAT = re.compile(r'\b\d{1,3}(?:[.,]\d+)?\s?(%|percent|x faster|times)', re.I)
FIELDS = ('slug', 'family', 'title', 'meta_description', 'h1', 'answer', 'sections', 'faq', 'internal_links', 'schema_type', 'sources', 'last_checked')


def _words(t):
    return len(re.findall(r'\w+', t or ''))


def check_page(p, where):
    errs, warns = [], []
    miss = [f for f in FIELDS if f not in p or p[f] in ('', None, [])]
    if miss:
        errs.append('%s: missing %s' % (where, ', '.join(miss)))
        return errs, warns
    if p['family'] not in FAMILIES:
        errs.append('%s: unknown family %s' % (where, p['family']))
    if not re.fullmatch(r'[a-z0-9][a-z0-9-]{0,80}', p['slug']):
        errs.append('%s: slug must be lowercase letters, digits and hyphens' % where)
    if len(p['title']) > 65:
        errs.append('%s: title is %d characters, keep it under 66' % (where, len(p['title'])))
    if not 70 <= len(p['meta_description']) <= 160:
        errs.append('%s: meta_description must be 70 to 160 characters (is %d)' % (where, len(p['meta_description'])))
    if not 25 <= _words(p['answer']) <= 70:
        errs.append('%s: answer must be 25 to 70 words, a direct answer a search engine or AI can quote (is %d)' % (where, _words(p['answer'])))
    if len(p['sections']) < 3 or any(not s.get('heading') or _words(s.get('body')) < 40 for s in p['sections']):
        errs.append('%s: needs at least 3 sections, each with a heading and 40 or more words' % where)
    if len(p['faq']) < 3 or any(not f.get('q') or _words(f.get('a')) < 15 for f in p['faq']):
        errs.append('%s: needs at least 3 FAQ items with answers of 15 or more words' % where)
    if len(p['internal_links']) < 3:
        errs.append('%s: needs at least 3 internal links' % where)
    if not p['sources']:
        errs.append('%s: every page lists its sources (url and date), or the single word "owner" for facts the owner supplied' % where)
    blob = json.dumps(p, ensure_ascii=False)
    if DASH.search(blob):
        errs.append('%s: contains an em or en dash, use a period, comma or colon' % where)
    if FAKE.search(blob):
        warns.append('%s: contains a hype or guarantee phrase' % where)
    if STAT.search(blob) and not any(isinstance(s, dict) and s.get('url') for s in p['sources']):
        errs.append('%s: contains a statistic but no source url' % where)
    return errs, warns


def validate(data):
    errs, warns, pages = [], [], []
    try:
        z = zipfile.ZipFile(io.BytesIO(data) if isinstance(data, (bytes, bytearray)) else data)
    except Exception as e:
        return {'ok': False, 'errors': ['Not a readable zip: %s' % e], 'warnings': [], 'pages': 0}
    names = set(z.namelist())
    for r in REQUIRED:
        if r not in names:
            errs.append('missing file %s' % r)
    try:
        man = json.loads(z.read('manifest.json'))
    except Exception:
        man = {}
        errs.append('manifest.json is not valid JSON')
    for k in ('pack_version', 'product', 'site', 'language', 'generated', 'page_count'):
        if k not in man:
            errs.append('manifest.json lacks %s' % k)
    seen_slug, seen_title = {}, {}
    for n in sorted(names):
        if not (n.startswith('pages/') and n.endswith('.json')):
            continue
        try:
            p = json.loads(z.read(n))
        except Exception:
            errs.append('%s is not valid JSON' % n)
            continue
        for item in (p if isinstance(p, list) else [p]):
            pages.append(item)
            e, w = check_page(item, n + ':' + str(item.get('slug', '?')))
            errs += e
            warns += w
            key = (item.get('family'), item.get('slug'))
            if key in seen_slug:
                errs.append('duplicate slug %s in %s and %s' % (item.get('slug'), seen_slug[key], n))
            seen_slug[key] = n
            t = (item.get('title') or '').strip().lower()
            if t and t in seen_title:
                errs.append('duplicate title "%s"' % item.get('title'))
            seen_title[t] = n
    if man.get('page_count') is not None and man.get('page_count') != len(pages):
        errs.append('manifest page_count %s does not match the %d pages found' % (man.get('page_count'), len(pages)))
    if not pages:
        errs.append('the pack contains no pages under pages/')
    thin = [p for p in pages if p.get('sections') and sum(_words(s.get('body')) for s in p['sections']) < 250]
    if len(thin) > max(2, len(pages) // 10):
        warns.append('%d pages are under 250 words, search engines treat thin pages as low value' % len(thin))
    return {'ok': not errs, 'errors': errs[:80], 'warnings': warns[:40], 'pages': len(pages), 'families': sorted({p.get('family') for p in pages if p.get('family')})}


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('usage: python seopack_validate.py pack.zip')
        sys.exit(2)
    r = validate(open(sys.argv[1], 'rb').read())
    print(json.dumps(r, indent=2, ensure_ascii=False))
    sys.exit(0 if r['ok'] else 1)
