#!/usr/bin/env python3
"""Offline XML well-formedness probe. Not sitemap/schema or SEO validation."""
import argparse
import json
from pathlib import Path
import sys
import xml.etree.ElementTree as ET

NS = '{http://www.sitemaps.org/schemas/sitemap/0.9}'
MAX_BYTES = 5 * 1024 * 1024
cases = {
    'valid_without_stylesheet': ('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://example.test/caffe</loc></url></urlset>', True),
    'valid_with_xslt_processing_instruction': ('<?xml-stylesheet type="text/xsl" href="fixture.xsl"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://example.test/caffe</loc></url></urlset>', True),
    'invalid_unescaped_ampersand': ('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://example.test/?a=1&b=2</loc></url></urlset>', False),
    'valid_two_urls': ('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://example.test/a</loc></url><url><loc>https://example.test/b</loc></url></urlset>', True),
    'well_formed_not_a_sitemap': ('<document/>', True),
    'well_formed_empty_loc': ('<urlset><loc/></urlset>', True),
}


def inspect_xml(data):
    """Read bytes in memory; never fetch URLs or apply stylesheets."""
    # Reject DTDs: this tool does not need declarations or custom entities.
    # Decode UTF-16/32 too, so a NUL-interleaved DOCTYPE cannot bypass the check.
    if len(data) > MAX_BYTES:
        raise ValueError('File oltre il limite di 5 MiB; nessun parsing eseguito.')
    if data.startswith((b'\xff\xfe\x00\x00', b'\x00\x00\xfe\xff', b'<\x00\x00\x00', b'\x00\x00\x00<')):
        raise ValueError('Codifica UTF-32 non supportata; nessun esito di ben-formazione disponibile.')
    if b'<!doctype' in data.lower().replace(b'\x00', b''):
        raise ValueError('DOCTYPE non supportato; nessun parsing eseguito.')
    try:
        root = ET.fromstring(data)
    except LookupError as exc:
        raise ValueError('Codifica XML non supportata; nessun esito di ben-formazione disponibile.') from exc
    except ET.ParseError as exc:
        return {'well_formed': False, 'error': str(exc), 'loc_count': None,
                'scope': 'Solo ben-formazione XML; nessuna validazione sitemap o SEO.'}
    return {'well_formed': True, 'root': root.tag,
            'loc_count': len(root.findall('.//' + NS + 'loc')),
            'scope': 'Solo ben-formazione XML; loc conta il namespace sitemap standard, non URL validati.'}


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--file', type=Path, help='XML locale opzionale; massimo 5 MiB, nessuna richiesta di rete')
    args = parser.parse_args(argv)
    if args.file is not None:
        try:
            # Bound the read too: a large input is never loaded in full.
            with args.file.open('rb') as handle:
                result = inspect_xml(handle.read(MAX_BYTES + 1))
        except (OSError, ValueError) as exc:
            print(str(exc), file=sys.stderr)
            return 2
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return 0 if result['well_formed'] else 1
    for name, (xml, expected_valid) in cases.items():
        result = inspect_xml(xml.encode('utf-8'))
        assert result['well_formed'] == expected_valid, f'{name}: {result}'
        print(f'{name}: {"PASS" if expected_valid else "INVALID AS EXPECTED"} — {result["scope"]}')
    return 0


if __name__ == '__main__':
    sys.exit(main())
