"""
fix_excel_for_libreoffice.py
----------------------------
Run this once on an xlsx downloaded from Excel Online before opening it in
LibreOffice Calc.  It removes the _xlfn. / _xlws. prefixes that Excel Online
injects into formulas — those prefixes make LibreOffice show #NAME? errors.

Usage:
    python3 fix_excel_for_libreoffice.py "TCG Sole Trader Copy.xlsx"

The original file is left untouched (a .bak copy is kept).
"""

import sys
import os
import re
import zipfile
import shutil

FORMULA_PREFIXES = re.compile(r'_xlfn\.|_xlws\.')


def fix_xlsx(path: str) -> None:
    if not os.path.exists(path):
        print(f"File not found: {path}")
        sys.exit(1)

    bak_path = path + '.bak'
    tmp_path = path + '.tmp'

    shutil.copy2(path, bak_path)
    print(f"Backup saved → {bak_path}")

    changes = 0

    with zipfile.ZipFile(path, 'r') as zin, \
         zipfile.ZipFile(tmp_path, 'w', zipfile.ZIP_DEFLATED) as zout:

        for item in zin.infolist():
            data = zin.read(item.filename)

            # Only patch sheet XML — leave everything else byte-for-byte identical
            if item.filename.startswith('xl/worksheets/sheet') and item.filename.endswith('.xml'):
                text = data.decode('utf-8')
                new_text, n = FORMULA_PREFIXES.subn('', text)
                if n:
                    print(f"  {item.filename}: removed {n} prefix(es)")
                    changes += n
                    data = new_text.encode('utf-8')

            zout.writestr(item, data)

    os.replace(tmp_path, path)

    if changes:
        print(f"\nDone — {changes} prefix(es) removed.  Open {path} in LibreOffice Calc.")
    else:
        print("\nNo _xlfn./_xlws. prefixes found — file was already clean.")
        os.remove(bak_path)


if __name__ == '__main__':
    if len(sys.argv) < 2:
        # Default to the workbook the scraper uses
        target = 'TCG Sole Trader Copy.xlsx'
    else:
        target = sys.argv[1]

    fix_xlsx(target)
