#!/usr/bin/env python3
"""Check whether one book file fits each document translator's per-file limits.

Usage: python3 fit_check.py book.epub [limits.json]
Accepts .epub, .docx or .txt only; for a PDF, save its text as .txt or
.docx first. Counts the visible text characters (spaces
included) and words, then compares them with the per-file limits in
limits.json. Character counts are estimates: each service counts text in
its own way, so leave headroom when a file is close to a limit.
"""
import html, json, math, os, re, sys, zipfile
from html.parser import HTMLParser
from urllib.parse import unquote

SUPPORTED = ("epub", "docx", "txt")

class Text(HTMLParser):
    SKIP = {"script", "style", "head"}
    def __init__(self):
        super().__init__(); self.parts = []; self.skip = 0
    def handle_starttag(self, tag, attrs):
        if tag in self.SKIP: self.skip += 1
        if tag in ("p", "div", "br", "li", "h1", "h2", "h3", "h4", "tr"): self.parts.append("\n")
    def handle_endtag(self, tag):
        if tag in self.SKIP and self.skip: self.skip -= 1
    def handle_data(self, data):
        if not self.skip: self.parts.append(data)

def markup_text(raw):
    p = Text(); p.feed(raw); return "".join(p.parts)

def epub_text(path):
    z = zipfile.ZipFile(path)
    container = z.read("META-INF/container.xml").decode()
    opf = re.search(r'full-path="([^"]+)"', container).group(1)
    base = os.path.dirname(opf)
    o = z.read(opf).decode()
    items = {m.group(1): m.group(2) for m in re.finditer(r'<item\b[^>]*\bid="([^"]+)"[^>]*\bhref="([^"]+)"', o)}
    items.update({m.group(2): m.group(1) for m in re.finditer(r'<item\b[^>]*\bhref="([^"]+)"[^>]*\bid="([^"]+)"', o)})
    spine = []
    for ref in re.findall(r"<itemref\b[^>]*>", o):
        if 'linear="no"' not in ref:
            spine.append(re.search(r'idref="([^"]+)"', ref).group(1))
    return "\n".join(markup_text(z.read(os.path.join(base, unquote(html.unescape(items[i])))).decode("utf-8", "replace")) for i in spine)

def docx_text(path):
    xml = zipfile.ZipFile(path).read("word/document.xml").decode()
    xml = re.sub(r"<w:delText\b[^>]*>.*?</w:delText>", "", xml, flags=re.S)
    xml = re.sub(r"<w:(tab|br|cr)\b[^>]*/>", " ", xml)
    return "\n".join(html.unescape(re.sub(r"<[^>]+>", "", p)) for p in re.findall(r"<w:p[ >].*?</w:p>", xml, re.S))

def read(path):
    ext = os.path.splitext(path)[1].lower()
    if ext == ".epub": return epub_text(path)
    if ext == ".docx": return docx_text(path)
    return open(path, encoding="utf-8", errors="replace").read()

def main():
    if len(sys.argv) < 2:
        sys.exit("usage: python3 fit_check.py book.epub|book.docx|book.txt [limits.json]")
    path = sys.argv[1]
    ext = os.path.splitext(path)[1].lower().lstrip(".")
    if ext not in SUPPORTED:
        sys.exit(f"Unsupported file type .{ext}: use .epub, .docx or .txt (save a PDF's text as .txt or .docx first).")
    limits = json.load(open(sys.argv[2] if len(sys.argv) > 2 else os.path.join(os.path.dirname(__file__), "limits.json")))
    text = re.sub(r"[ \t\r\f\v]+", " ", read(path))
    text = re.sub(r"\n\s*", "\n", text).strip()
    chars, words = len(text), len(text.split())
    mb = os.path.getsize(path) / 1_000_000
    print(f"{os.path.basename(path)}: {chars:,} characters, {words:,} words, {mb:.1f} MB as .{ext}")
    print(f"Limits checked {limits['checked']}. Character counts are estimates; MB means 1,000,000 bytes.\n")
    for o in limits["options"]:
        lim = o["limits"].get(ext)
        if lim is None:
            print(f"- {o['name']}: does not accept .{ext} ({o['source']})"); continue
        notes = []
        if lim.get("max_mb") and mb > lim["max_mb"]: notes.append(f"file over {lim['max_mb']} MB")
        if lim.get("max_chars"):
            parts = math.ceil(chars / lim["max_chars"])
            if parts > 1: notes.append(f"over {lim['max_chars']:,} characters: at least {parts} parts")
        if lim.get("max_words") and words > lim["max_words"]: notes.append(f"over {lim['max_words']:,} words per task")
        verdict = "fits as one file" if not notes else "; ".join(notes)
        extra = f" Note: {o['note']}" if o.get("note") else ""
        print(f"- {o['name']}: {verdict}.{extra}")

if __name__ == "__main__":
    main()
