# -*- coding: utf-8 -*-
# ###
# Copyright (c) 2016, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
"""\
Processes a collated book's single-html representation for validation
and parser of specific elements.

"""
import argparse
import os
import sys
from pprint import pprint

import cnxepub


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('collated_html', type=argparse.FileType('r'),
                        help='Path to the collated html file (use - for stdin)')
    args = parser.parse_args(argv)

    binder = cnxepub.adapt_single_html(args.collated_html.read())
    pprint(cnxepub.model_to_tree(binder))

    # TODO Check for documents that have no identifier.
    #      These should likely be composite-documents
    #      or the the metadata got whiped out.
    # docs = [x for x in cnxepub.flatten_to(binder, only_documents_filter)
    #         if x.ident_hash is None]

    return 0

# -*- coding: utf-8 -*-
# ###
# Copyright (c) 2016, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
"""Processes a collated book's single-html representation for validation.

Ensures safe parsing for specific elements.
"""
import argparse
import logging
import sys
from pprint import pprint
from lxml import etree
import cnxepub

logger = logging.getLogger('cnxepub')

formatter = logging.Formatter('%(name)s %(levelname)s %(message)s')
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(formatter)
logger.addHandler(handler)


def main(argv=None):
    """Parse passed in cooked single HTML."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('collated_html', type=argparse.FileType('r'),
                        help='Path to the collated html'
                             ' file (use - for stdin)')
    parser.add_argument('-d', '--dump-tree', action='store_true',
                        help='Print out parsed model tree.')

    args = parser.parse_args(argv)

    html = args.collated_html.read()
    try:
        htree = etree.fromstring(html)
    except etree.XMLSyntaxError:
        htree = etree.HTML(html)

    xhtml = etree.tostring(htree, encoding='utf-8')

    binder = cnxepub.adapt_single_html(xhtml)
    if args.dump_tree:
        pprint(cnxepub.model_to_tree(binder))

    # TODO Check for documents that have no identifier.
    #      These should likely be composite-documents
    #      or the the metadata got wiped out.
    # docs = [x for x in cnxepub.flatten_to(binder, only_documents_filter)
    #         if x.ident_hash is None]

    return 0

Make validation script quiet by default (tree dump behind -d/--dump-tree); add logging ouput support