"""Offline teaching preflight. Does not emulate a crawler or modify an input."""
import gzip
import hashlib
from pathlib import Path
import xml.etree.ElementTree as ET

ROBOTS_LIMIT = 500 * 1024
SITEMAP_LIMIT = 52_428_800
URL_LIMIT = 50_000
NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'

def robots(data):
    out = {'sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data),
           'googleDocumentedLimitBytes': ROBOTS_LIMIT, 'beyondLimit': len(data) > ROBOTS_LIMIT,
           'scope': 'UTF-8 and byte envelope only; no group selection or rule matching'}
    try:
        text = data.decode('utf-8')
    except UnicodeDecodeError:
        return {**out, 'utf8': False, 'characters': None, 'lines': [], 'status': 'INVALID_UTF8_REVIEW'}
    offset = 0
    lines = []
    # CR, LF and CRLF only, rather than Python's wider Unicode splitlines set.
    import re
    for line in re.findall(rb'[^\r\n]*(?:\r\n|\r|\n|$)', data):
        if not line:
            continue
        end = offset + len(line)
        lines.append({'startByte': offset, 'endByteExclusive': end,
                      'withinEnvelope': end <= ROBOTS_LIMIT,
                      'crossesBoundary': offset < ROBOTS_LIMIT < end})
        offset = end
    return {**out, 'utf8': True, 'characters': len(text), 'lines': lines,
            'status': 'OVERSIZE_REVIEW' if out['beyondLimit'] else 'WITHIN_BYTE_ENVELOPE_ONLY'}

def sitemap(path):
    path = Path(path)
    compressed = path.suffix == '.gz'
    # Stop at limit+1; don't fully expand an oversized gzip input.
    opener = gzip.open if compressed else open
    try:
        with opener(path, 'rb') as f:
            data = f.read(SITEMAP_LIMIT + 1)
    except (OSError, EOFError):
        return {'status': 'READ_OR_GZIP_FAILED', 'compressed': compressed}
    out = {'compressed': compressed, 'storedBytes': path.stat().st_size,
           'bytesReadUncompressed': len(data), 'byteLimit': SITEMAP_LIMIT,
           'urlLimit': URL_LIMIT, 'scope': 'Ordinary urlset only; no extensions/index/crawl/indexing acceptance'}
    if len(data) > SITEMAP_LIMIT:
        return {**out, 'status': 'UNCOMPRESSED_LIMIT_EXCEEDED', 'urlEntries': None,
                'exactTotalUncompressedBytes': None}
    out['exactTotalUncompressedBytes'] = len(data)
    try:
        data.decode('utf-8')
        if b'<!DOCTYPE' in data.upper() or b'<!ENTITY' in data.upper():
            return {**out, 'status': 'UNSUPPORTED_DECLARATION'}
        root = ET.fromstring(data)
    except (UnicodeDecodeError, ET.ParseError):
        return {**out, 'status': 'UTF8_OR_XML_INVALID'}
    if root.tag != '{' + NS + '}urlset':
        return {**out, 'status': 'UNSUPPORTED_ROOT'}
    entries = root.findall('{' + NS + '}url')
    urls = [e.findtext('{' + NS + '}loc') for e in entries]
    if any(u is None or not u.strip() for u in urls):
        return {**out, 'status': 'MISSING_LOC', 'urlEntries': len(entries)}
    return {**out, 'status': 'URL_LIMIT_EXCEEDED' if len(entries) > URL_LIMIT else 'WITHIN_TWO_LIMITS_ONLY',
            'urlEntries': len(entries), 'distinctLocStrings': len(set(urls)),
            'parsedLocSha256': hashlib.sha256('\n'.join(urls).encode()).hexdigest()}

if __name__ == '__main__':
    import argparse, json
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('kind', choices=['robots', 'sitemap'])
    p.add_argument('input')
    a = p.parse_args()
    print(json.dumps(robots(Path(a.input).read_bytes()) if a.kind == 'robots' else sitemap(a.input), indent=2))
