#!/usr/bin/env python3
"""Check an EPUB's table of contents, or compare it with its translation.

    python3 check_epub_toc.py book.epub
    python3 check_epub_toc.py original.epub translated.epub

Needs Python 3 only. Reads the files and changes nothing.
A two-language file holds both languages in its labels, so its nav and NCX can
differ by design. Check the single-language file instead.
Exit code: 0 no problems, 1 problems found, 2 the file could not be read.
"""
import posixpath
import re
import sys
import xml.etree.ElementTree as ET
import zipfile
import zlib
from urllib.parse import unquote, urlsplit

NCX_TYPE = "application/x-dtbncx+xml"
EPUB_NS = "{http://www.idpf.org/2007/ops}"
READ_ERRORS = (OSError, KeyError, IndexError, TypeError, ValueError, LookupError, zlib.error, zipfile.BadZipFile, ET.ParseError)


def local(el):
    return el.tag.rsplit("}", 1)[-1]


def text_of(el):
    parts = []

    def walk(node):
        if isinstance(node.tag, str) and local(node) == "br":
            parts.append(" ")
        parts.append(node.text or "")
        for child in node:
            walk(child)
            parts.append(child.tail or "")

    walk(el)
    return " ".join("".join(parts).split())


def find_all(root, name):
    return [el for el in root.iter() if isinstance(el.tag, str) and local(el) == name]


class Book:
    def __init__(self, path):
        self.zip = zipfile.ZipFile(path)
        self.names = set(self.zip.namelist())
        container = ET.fromstring(self.zip.read("META-INF/container.xml"))
        self.opf_path = find_all(container, "rootfile")[0].get("full-path")
        self.opf_dir = posixpath.dirname(self.opf_path)
        opf = ET.fromstring(self.zip.read(self.opf_path))
        self.version = opf.get("version", "?")
        items = find_all(opf, "item")
        self.nav_path = self.ncx_path = None
        for item in items:
            href = posixpath.normpath(posixpath.join(self.opf_dir, unquote(item.get("href", ""))))
            if "nav" in (item.get("properties") or "").split():
                self.nav_path = href
            if item.get("media-type") == NCX_TYPE:
                self.ncx_path = href
        self.nav_title, self.nav_unlinked = None, []
        self.nav = self._read_nav() if self.nav_path in self.names else []
        self.ncx_title = None
        self.ncx = self._read_ncx() if self.ncx_path in self.names else []

    def _resolve(self, base, href):
        parts = urlsplit(href)
        if not parts.path:
            return base, unquote(parts.fragment)
        path = posixpath.normpath(posixpath.join(posixpath.dirname(base), unquote(parts.path)))
        return path, unquote(parts.fragment)

    def _read_nav(self):
        root = ET.fromstring(self.zip.read(self.nav_path))
        navs = find_all(root, "nav")
        toc = next((n for n in navs if n.get(EPUB_NS + "type") == "toc"), navs[0] if navs else None)
        if toc is None:
            return []
        headings = [el for el in toc.iter() if isinstance(el.tag, str) and re.fullmatch("h[1-6]", local(el))]
        self.nav_title = text_of(headings[0]) if headings else None
        links = find_all(toc, "a")
        inside = {el for a in links for el in a.iter()}
        self.nav_unlinked = [text_of(el) for el in find_all(toc, "span") if el not in inside and text_of(el)]
        return [
            (text_of(a), *self._resolve(self.nav_path, a.get("href", "")))
            for a in links
            if not urlsplit(a.get("href", "")).scheme
        ]

    def _read_ncx(self):
        root = ET.fromstring(self.zip.read(self.ncx_path))
        titles = find_all(root, "docTitle")
        self.ncx_title = text_of(titles[0]) if titles else None
        out = []
        for point in find_all(root, "navPoint"):
            label = next((el for el in point if local(el) == "navLabel"), None)
            content = next((el for el in point if local(el) == "content"), None)
            if content is not None and not urlsplit(content.get("src", "")).scheme:
                out.append((text_of(label) if label is not None else "", *self._resolve(self.ncx_path, content.get("src", ""))))
        return out

    def has_target(self, path, fragment):
        if path not in self.names:
            return False
        if not fragment:
            return True
        doc = self.zip.read(path).decode("utf-8", "replace")
        return re.search(r"""(?<![\w-])(?:id|name)\s*=\s*["']%s["']""" % re.escape(fragment), doc) is not None


def check_one(book, problems):
    print(f"EPUB version {book.version}")
    print(f"  nav document: {book.nav_path or 'none'} ({len(book.nav)} links)")
    print(f"  NCX file:     {book.ncx_path or 'none'} ({len(book.ncx)} entries)")
    if book.version.startswith("3") and not book.nav_path:
        problems.append("EPUB 3 file has no nav document")
    for name, path in (("nav document", book.nav_path), ("NCX file", book.ncx_path)):
        if path and path not in book.names:
            problems.append(f"{name} is listed in the package but missing from the file: {path}")
    if not book.nav and not book.ncx:
        problems.append("no table of contents entries found")
    for name, entries in (("nav", book.nav), ("NCX", book.ncx)):
        for label, path, fragment in entries:
            if path not in book.names:
                problems.append(f"{name}: '{label}' points to a missing file: {path}")
            elif not book.has_target(path, fragment):
                problems.append(f"{name}: '{label}' points to a missing anchor: {path}#{fragment}")
    if book.nav and book.ncx:
        nav_targets = [(p, f) for _, p, f in book.nav]
        ncx_targets = [(p, f) for _, p, f in book.ncx]
        if len(nav_targets) != len(ncx_targets):
            problems.append(f"nav has {len(nav_targets)} links but NCX has {len(ncx_targets)} entries")
        if sorted(nav_targets) != sorted(ncx_targets):
            for p, f in sorted(set(nav_targets) ^ set(ncx_targets)):
                problems.append(f"nav and NCX disagree on target: {p}{'#' + f if f else ''}")
        elif nav_targets != ncx_targets:
            problems.append("nav and NCX list the same targets in a different order")
        ncx_by_target = {}
        for label, p, f in book.ncx:
            ncx_by_target.setdefault((p, f), []).append(label)
        for label, p, f in book.nav:
            queue = ncx_by_target.get((p, f))
            if queue:
                other = queue.pop(0)
                if other != label:
                    problems.append(f"nav says '{label}' but NCX says '{other}'")


def compare(src, out, problems):
    print("\nCompared with the original:")
    pairs = [("nav", src.nav, out.nav), ("NCX", src.ncx, out.ncx)]
    for name, before, after in pairs:
        if before and not after:
            problems.append(f"{name}: present in the original, missing in the translation")
            continue
        if len(before) != len(after):
            problems.append(f"{name}: {len(before)} entries in the original, {len(after)} in the translation")
        same = [b[0] for b, a in zip(before, after) if b[0] == a[0] and re.search(r"[^\W\d_]", b[0])]
        if before:
            print(f"  {name}: {len(same)} of {len(before)} labels unchanged")
        for label in same:
            problems.append(f"{name}: label not translated: '{label}'")
        for b, a in zip(before, after):
            if b[1:] != a[1:]:
                problems.append(f"{name}: '{a[0]}' changed target from {b[1]}#{b[2]} to {a[1]}#{a[2]}")
    extras = [("nav heading", src.nav_title, out.nav_title), ("NCX title", src.ncx_title, out.ncx_title)]
    for name, before, after in extras:
        if before and before == after:
            problems.append(f"{name} not translated: '{before}'")
    for before, after in zip(src.nav_unlinked, out.nav_unlinked):
        if before == after:
            problems.append(f"nav section label without a link not translated: '{before}'")


def main(argv):
    if len(argv) not in (2, 3):
        print(__doc__)
        return 2
    problems = []
    try:
        books = [Book(path) for path in argv[1:]]
        check_one(books[-1], problems)
        if len(books) == 2:
            compare(books[0], books[1], problems)
    except READ_ERRORS as err:
        print(f"Could not read the EPUB: {err}")
        return 2
    print()
    if problems:
        print(f"{len(problems)} problem(s):")
        for line in problems:
            print(f"  - {line}")
        return 1
    print("No table of contents problems found.")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
