#!/usr/bin/env python3
"""epub_triage.py - find out why an EPUB will not open, before reaching for a repair tool.

Usage:  python3 epub_triage.py book.epub
Uses only the Python 3 standard library and never modifies the file.
It checks the layers in the order a reader opens them: file type, ZIP archive,
mimetype, container.xml, package document (.opf), DRM, manifest, and chapters.
"""
import posixpath, sys, zipfile
from urllib.parse import unquote
import xml.etree.ElementTree as ET

OPF_NS = '{http://www.idpf.org/2007/opf}'
FONT_OBFUSCATION = {'http://www.idpf.org/2008/embedding', 'http://ns.adobe.com/pdf/enc#RC'}
findings = []

def report(level, layer, message):
    findings.append((level, layer, message))

def finish():
    worst = 'OK'
    for level, layer, message in findings:
        print(f'[{level:5}] {layer}: {message}')
        if level == 'FAIL' or (level == 'WARN' and worst == 'OK'):
            worst = level
    verdicts = {
        'OK': 'No structural problem found. If a reader still refuses it, try another reader app before editing the file.',
        'WARN': 'The book is readable but not to spec. Most readers open it; strict ones may not.',
        'FAIL': 'Fix the first FAIL above first: later checks depend on it.',
    }
    print(f'\nResult: {worst}. {verdicts[worst]}')
    sys.exit(0 if worst != 'FAIL' else 1)

def main(path):
    try:
        head = open(path, 'rb').read(512)
    except OSError as e:
        sys.exit(f'Cannot read {path}: {e.strerror}')
    if not head.startswith(b'PK\x03\x04'):
        text = head.decode('utf-8', 'replace').lstrip().lower()
        if text.startswith('<fulfillmenttoken'):
            report('FAIL', 'file type', 'This is an Adobe ACSM licence file, not a book. Open it in Adobe Digital Editions to download the actual (DRM-protected) EPUB.')
        elif text.startswith('<!doctype html') or text.startswith('<html'):
            report('FAIL', 'file type', 'This is a saved web page, not an EPUB. The download link probably returned an error or login page.')
        else:
            report('FAIL', 'file type', 'The file does not start with a ZIP signature, so it is not an EPUB container.')
        return finish()
    try:
        z = zipfile.ZipFile(path)
    except zipfile.BadZipFile as e:
        report('FAIL', 'zip', f'The ZIP index at the end of the file is missing or broken ({e}). This usually means an interrupted download: download it again. Content that did arrive may still be recoverable.')
        return finish()
    names = z.namelist()
    if not names:
        report('FAIL', 'zip', 'The archive is empty.')
        return finish()
    bad = []
    for info in z.infolist():
        try:
            data = z.read(info.filename)
            if len(data) != info.file_size:
                bad.append(f'{info.filename} (size)')
        except Exception as e:
            bad.append(f'{info.filename} ({type(e).__name__})')
    if bad:
        report('FAIL', 'zip', 'Entries that cannot be read back intact: ' + ', '.join(bad[:10]) + '. Re-download, or re-pack the archive from its raw entries.')
    else:
        report('OK', 'zip', f'{len(names)} entries, all readable and CRC-checked.')

    first = z.infolist()[0]
    if 'mimetype' not in names:
        report('WARN', 'mimetype', 'No mimetype file. Many readers still open the book; strict validators reject it.')
    else:
        content = z.read('mimetype')
        problems = []
        if first.filename != 'mimetype': problems.append('it is not the first entry')
        if z.getinfo('mimetype').compress_type != zipfile.ZIP_STORED: problems.append('it is compressed')
        if content != b'application/epub+zip': problems.append(f'its content is {content[:40]!r}')
        if problems:
            report('WARN', 'mimetype', 'The mimetype file breaks the EPUB rule: ' + '; '.join(problems) + '. This happens when a folder is re-zipped with an ordinary ZIP tool.')
        else:
            report('OK', 'mimetype', 'First entry, stored uncompressed, correct content.')

    opfs = [n for n in names if n.lower().endswith('.opf')]
    declared = None
    if 'META-INF/container.xml' not in names:
        report('FAIL', 'container', 'META-INF/container.xml is missing, so a reader cannot find the package document.')
    else:
        try:
            root = ET.fromstring(z.read('META-INF/container.xml'))
            rf = root.find('.//{urn:oasis:names:tc:opendocument:xmlns:container}rootfile')
            declared = rf.get('full-path') if rf is not None else None
            if not declared:
                report('FAIL', 'container', 'container.xml has no rootfile with a full-path, so a reader cannot find the package document.')
        except ET.ParseError as e:
            report('FAIL', 'container', f'container.xml is not well-formed XML ({e}).')
        if declared and declared not in names:
            hint = f' The archive holds {opfs[0]}; point full-path at it.' if len(opfs) == 1 else ''
            report('FAIL', 'container', f'container.xml points to {declared}, which is not in the archive.{hint}')
        elif declared:
            report('OK', 'container', f'Package document: {declared}')
    opf_path = declared if declared in names else (opfs[0] if len(opfs) == 1 else None)
    if not opfs:
        report('FAIL', 'package', 'There is no .opf package document anywhere in the archive. Nothing lists the chapters, so re-download or re-export the book.')
        return finish()
    if opf_path is None:
        report('FAIL', 'package', f'Cannot tell which of {len(opfs)} .opf files is the package document.')
        return finish()

    if 'META-INF/encryption.xml' in names:
        try:
            enc = ET.fromstring(z.read('META-INF/encryption.xml'))
            algos = {el.get('Algorithm') for el in enc.iter() if el.tag.endswith('EncryptionMethod')}
        except ET.ParseError as e:
            algos = None
            report('FAIL', 'DRM', f'encryption.xml is not well-formed XML ({e}); treat the book as possibly encrypted.')
        if algos is not None:
            if not algos:
                report('WARN', 'DRM', 'encryption.xml is present but names no encryption method; check it by hand.')
            elif algos - FONT_OBFUSCATION:
                report('FAIL', 'DRM', 'encryption.xml encrypts content, not just fonts. This is DRM; no repair step applies.')
            else:
                report('OK', 'DRM', 'encryption.xml only obfuscates fonts; that is not DRM.')

    try:
        pkg = ET.fromstring(z.read(opf_path))
    except ET.ParseError as e:
        report('FAIL', 'package', f'{opf_path} is not well-formed XML ({e}).')
        return finish()
    base = posixpath.dirname(opf_path)
    items = {i.get('id'): i for i in pkg.iter(OPF_NS + 'item')}
    missing = [i.get('href') for i in items.values() if '://' not in i.get('href', '') and posixpath.normpath(posixpath.join(base, unquote(i.get('href', '')))) not in names]
    if missing:
        report('FAIL', 'manifest', f'{len(missing)} file(s) listed in the manifest are not in the archive: ' + ', '.join(missing[:10]))
    else:
        report('OK', 'manifest', f'All {len(items)} manifest items are present.')

    spine = [r.get('idref') for r in pkg.iter(OPF_NS + 'itemref')]
    broken, empty, checked = [], [], 0
    for idref in spine:
        item = items.get(idref)
        if item is None: continue
        p = posixpath.normpath(posixpath.join(base, unquote(item.get('href', ''))))
        if p not in names: continue
        try:
            raw = z.read(p)
        except Exception:
            continue
        checked += 1
        text = raw.decode('utf-8', 'replace').lstrip('﻿').strip()
        if not text or not text.startswith('<'):
            empty.append(item.get('href'))
            continue
        try:
            ET.fromstring(raw)
        except ET.ParseError as e:
            broken.append(f"{item.get('href')} ({e})")
    if empty:
        level = 'FAIL' if len(empty) * 2 >= len(spine) else 'WARN'
        report(level, 'chapters', f'{len(empty)} of {len(spine)} spine documents are empty or plain text, not XHTML: ' + ', '.join(empty[:10]) + '. A bookstore download that failed part-way often looks like this.')
    if broken:
        report('WARN', 'chapters', 'Not well-formed XHTML (lenient readers may still show it): ' + '; '.join(broken[:5]))
    if not empty and not broken:
        report('OK', 'chapters', f'{checked} of {len(spine)} spine documents checked; all well-formed XHTML.' if checked < len(spine) else f'All {len(spine)} spine documents are well-formed XHTML.')
    finish()

if __name__ == '__main__':
    if len(sys.argv) != 2:
        sys.exit('usage: python3 epub_triage.py book.epub')
    main(sys.argv[1])
