"""Offline teaching checker. No fetches, website changes, or Google simulation."""
import json
import re
import sys
from html.parser import HTMLParser

VOID = {'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link',
        'meta', 'param', 'source', 'track', 'wbr'}
SUPPORTED = {'span', 'div', 'section'}


class Capture(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.stack, self.errors, self.warnings = [], [], []
        self.ordinary, self.excluded, self.directives = [], [], []
        self.json_ld = False

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        attr = 'data-nosnippet' in a
        if attr and tag not in SUPPORTED:
            self.warnings.append('UNSUPPORTED_ATTRIBUTE_ELEMENT:' + tag)
        if tag == 'meta' and a.get('name', '').lower() in {'robots', 'googlebot'}:
            self.directives.append(a.get('content', ''))
        if tag == 'script' and a.get('type', '').lower() == 'application/ld+json':
            self.json_ld = True
        if tag not in VOID:
            self.stack.append((tag, attr and tag in SUPPORTED))

    def handle_startendtag(self, tag, attrs):
        self.handle_starttag(tag, attrs)
        if tag not in VOID:
            self.handle_endtag(tag)

    def handle_endtag(self, tag):
        if tag in VOID:
            return
        if not self.stack or self.stack[-1][0] != tag:
            self.errors.append('UNBALANCED_TAG:' + tag)
            return
        self.stack.pop()

    def handle_data(self, data):
        if any(t in {'head', 'script', 'style', 'template'} for t, _ in self.stack):
            return
        if data.strip():
            (self.excluded if any(x for _, x in self.stack) else self.ordinary).append(data)


def check(record):
    if not isinstance(record, dict) or not isinstance(record.get('html'), str) or not record['html'].strip():
        raise ValueError('Nonempty html string required')
    if not isinstance(record.get('id'), str) or not record['id']:
        raise ValueError('Nonempty id required')
    if record.get('crawlAllowed') is not None and type(record.get('crawlAllowed')) is not bool:
        raise ValueError('crawlAllowed must be a boolean or null')
    headers = record.get('xRobotsTag', [])
    if not isinstance(headers, list) or any(not isinstance(h, str) for h in headers):
        raise ValueError('xRobotsTag must be an array of strings')
    p = Capture()
    p.feed(record['html'])
    p.close()
    if p.stack:
        p.errors.append('UNCLOSED_TAGS:' + ','.join(t for t, _ in p.stack))
    rules = list(p.directives)
    for h in headers:
        scoped = re.match(r'^\s*([\w-]+)\s*:\s*(.*)$', h)
        if scoped and scoped[1].lower() not in {'max-snippet', 'max-image-preview', 'max-video-preview', 'unavailable_after'}:
            if scoped[1].lower() == 'googlebot':
                rules.append(scoped[2])
            else:
                p.warnings.append('OTHER_AGENT_HEADER_NOT_APPLIED')
        else:
            rules.append(h)
    tokens = [x.strip().lower() for value in rules for x in value.split(',')]
    noindex = 'noindex' in tokens or 'none' in tokens
    limits = []
    for t in tokens:
        if t.startswith('max-snippet:'):
            try:
                n = int(t.split(':', 1)[1].strip())
                if n < -1:
                    raise ValueError()
                if n >= 0:
                    limits.append(n)
            except ValueError:
                p.warnings.append('INVALID_MAX_SNIPPET')
    suppressed = 'nosnippet' in tokens or 0 in limits
    intent = record.get('intent', 'exclude_selected_preview_text')
    if intent not in {'keep_secret', 'prevent_phrase_indexing', 'exclude_selected_preview_text'}:
        raise ValueError('Unsupported intent value')
    if intent in {'keep_secret', 'prevent_phrase_indexing'}:
        verdict = 'UNSUPPORTED_GOAL'
    elif record.get('crawlAllowed') is not True:
        verdict = 'UNKNOWN_CRAWLER_ACCESS'
    elif p.errors:
        verdict = 'REPAIR_INPUT_HTML'
    elif noindex:
        verdict = 'PAGE_INDEXING_RESTRICTED'
    elif suppressed:
        verdict = 'WHOLE_PAGE_TEXT_PREVIEW_RESTRICTED'
    elif p.warnings:
        verdict = 'REVIEW_WARNINGS'
    elif p.excluded:
        verdict = 'SECTION_BOUNDARY_PRESENT_IN_SUPPLIED_HTML'
    else:
        verdict = 'NO_SECTION_BOUNDARY_FOUND'
    clean = lambda a: re.sub(r'\s+', ' ', ' '.join(a)).strip()
    return {
        'id': record['id'], 'verdict': verdict,
        'ordinaryTextInSuppliedHtml': clean(p.ordinary),
        'sectionExcludedTextInSuppliedHtml': clean(p.excluded),
        'declaredPageNoindex': noindex, 'declaredWholePageNoTextPreview': suppressed,
        'declaredMaxSnippet': min(limits) if limits else None,
        'structuredDataNeedsSeparateReview': p.json_ld,
        'errors': p.errors, 'warnings': p.warnings,
        'googleObservedResult': None,
        'limit': 'Strict balanced-HTML teaching subset; not a browser parser, crawler, indexing test, privacy control or prediction of Google snippets/AI answers.'
    }


if __name__ == '__main__':
    try:
        with open(sys.argv[1], encoding='utf-8') as f:
            records = json.load(f)
        if not isinstance(records, list):
            raise ValueError('Input must be an array')
        results = [check(r) for r in records]
        ids = [r['id'] for r in records]
        if len(set(ids)) != len(records):
            raise ValueError('IDs must be unique')
        print(json.dumps(results, ensure_ascii=False, indent=2))
    except (ValueError, IndexError, OSError) as e:
        print(json.dumps({'error': str(e)}), file=sys.stderr)
        sys.exit(2)
