#!/usr/bin/env python3
"""
Extract clean plain text from a .docx (e.g. a Teams meeting transcript).

A .docx is a ZIP; the text lives in word/document.xml. Transcript text is small
even when the file is large -- a 3 MB transcript docx was 56 KB of text, the
rest being embedded images.

Use this only for files genuinely on local disk. For documents that live in
SharePoint/OneDrive, use WorkIQ Ask so permissions and sensitivity labels are
honoured.

Usage:
    python extract-docx-text.py <input.docx> [output.txt]

If output.txt is omitted, writes alongside the input with a .txt extension.
"""

import sys
import os
import re
import html
import zipfile


def extract(path: str) -> str:
    with zipfile.ZipFile(path) as z:
        xml = z.read("word/document.xml").decode("utf8", "ignore")

    # paragraph and line-break boundaries -> newlines
    xml = re.sub(r"</w:p>", "\n", xml)
    xml = re.sub(r"<w:br[^>]*/>", "\n", xml)
    # drop all remaining tags
    xml = re.sub(r"<[^>]+>", "", xml)

    text = html.unescape(xml)
    lines = [ln.strip() for ln in text.split("\n")]
    return "\n".join(ln for ln in lines if ln)


def main() -> int:
    if len(sys.argv) < 2:
        print(__doc__)
        return 1

    src = sys.argv[1]
    if not os.path.isfile(src):
        print(f"not found: {src}")
        return 1

    dst = sys.argv[2] if len(sys.argv) > 2 else os.path.splitext(src)[0] + ".txt"

    out = extract(src)
    with open(dst, "w", encoding="utf8") as fh:
        fh.write(out)

    print(f"chars: {len(out)}")
    print(f"lines: {len(out.splitlines())}")
    print(f"saved: {dst}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
