#!/usr/bin/env python3
"""Copy table of contents labels between nav and NCX in an EPUB.

    python3 sync_epub_toc.py translated.epub fixed.epub --from nav
    python3 sync_epub_toc.py translated.epub fixed.epub --from ncx

Labels are matched by the file and anchor they point to, in order when several
entries share a target. Entries whose target appears on only one side are left
alone and listed. Links and chapters do not change, and the input file is not
modified. Inline markup inside a rewritten label, and the comments and DOCTYPE
of the rewritten file, are not kept. Use it on single-language files: it cannot
tell a two-language file apart. Needs Python 3 only.
"""
import argparse
import os
import sys
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from urllib.parse import urlsplit

from check_epub_toc import EPUB_NS, READ_ERRORS, Book, find_all, local, text_of

ET.register_namespace("", "http://www.w3.org/1999/xhtml")
ET.register_namespace("epub", EPUB_NS.strip("{}"))
NCX_NS = "http://www.daisy.org/z3986/2005/ncx/"


def set_nav(book, data, labels):
    ET.register_namespace("", "http://www.w3.org/1999/xhtml")
    root = ET.fromstring(data)
    navs = find_all(root, "nav")
    toc = next((n for n in navs if n.get(EPUB_NS + "type") == "toc"), navs[0])
    changed, missing = 0, []
    for a in find_all(toc, "a"):
        if urlsplit(a.get("href", "")).scheme:
            continue
        target = book._resolve(book.nav_path, a.get("href", ""))
        if not labels.get(target):
            missing.append(text_of(a))
            continue
        label = labels[target].pop(0)
        if not label:
            missing.append(text_of(a))
        elif text_of(a) != label:
            for child in list(a):
                a.remove(child)
            a.text = label
            changed += 1
    return ET.tostring(root, encoding="utf-8", xml_declaration=True), changed, missing


def set_ncx(book, data, labels):
    ET.register_namespace("", NCX_NS)
    root = ET.fromstring(data)
    changed, missing = 0, []
    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)
        text = next((el for el in label if local(el) == "text"), None) if label is not None else None
        if content is None or text is None:
            continue
        if urlsplit(content.get("src", "")).scheme:
            continue
        target = book._resolve(book.ncx_path, content.get("src", ""))
        if not labels.get(target):
            missing.append(text_of(label))
            continue
        new_label = labels[target].pop(0)
        if not new_label:
            missing.append(text_of(label))
        elif text_of(text) != new_label:
            text.text = new_label
            changed += 1
    return ET.tostring(root, encoding="utf-8", xml_declaration=True), changed, missing


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("input")
    parser.add_argument("output")
    parser.add_argument("--from", dest="source", choices=["nav", "ncx"], required=True, help="the side that already has the right labels")
    args = parser.parse_args()
    if os.path.lexists(args.output):
        sys.exit(f"{args.output} already exists. Choose a new output file; this script never overwrites anything.")
    try:
        book = Book(args.input)
        if not book.nav or not book.ncx:
            sys.exit("This EPUB does not have both a nav document and an NCX file, so there is nothing to sync.")
        entries = book.nav if args.source == "nav" else book.ncx
        labels = {}
        for label, path, fragment in entries:
            labels.setdefault((path, fragment), []).append(label)
        target_path = book.ncx_path if args.source == "nav" else book.nav_path
        update = set_ncx if args.source == "nav" else set_nav
        new_data, changed, missing = update(book, book.zip.read(target_path), labels)
    except READ_ERRORS as err:
        sys.exit(f"Could not read the EPUB: {err}")
    temp_path = None
    try:
        handle, temp_path = tempfile.mkstemp(suffix=".epub", dir=os.path.dirname(os.path.abspath(args.output)))
        with os.fdopen(handle, "wb") as raw, zipfile.ZipFile(raw, "w") as out:
            for info in book.zip.infolist():
                data = new_data if info.filename == target_path else book.zip.read(info.filename)
                kind = zipfile.ZIP_STORED if info.filename == "mimetype" else zipfile.ZIP_DEFLATED
                out.writestr(info.filename, data, compress_type=kind)
        os.chmod(temp_path, 0o644)
        os.replace(temp_path, args.output)
    except READ_ERRORS as err:
        if temp_path and os.path.exists(temp_path):
            os.remove(temp_path)
        sys.exit(f"Could not write {args.output}: {err}")
    print(f"Updated {changed} label(s) in {target_path}.")
    for label in missing:
        print(f"  No usable label in {args.source}, left as is: {label}")
    for leftovers in labels.values():
        for label in leftovers:
            print(f"  Only in {args.source}, not copied: {label}")


if __name__ == "__main__":
    main()
