#!/usr/bin/env python3
"""
Excel Formula Recalculation Script
Recalculates all formulas in an Excel file using LibreOffice
"""

import json
import os
import platform
import shutil
import subprocess
import sys
from pathlib import Path

from openpyxl import load_workbook


def resolve_soffice_binary():
    """Find a working LibreOffice executable."""
    candidates = ["soffice", "soffice.com", "soffice.exe"]
    if platform.system() == "Windows":
        candidates = ["soffice.com", "soffice.exe", "soffice"]

    for name in candidates:
        binary = shutil.which(name)
        if binary:
            return binary

    if platform.system() == "Windows":
        possible_roots = [
            os.environ.get("ProgramFiles"),
            os.environ.get("ProgramFiles(x86)"),
        ]
        for root in possible_roots:
            if not root:
                continue
            for rel in [
                "LibreOffice/program/soffice.com",
                "LibreOffice/program/soffice.exe",
            ]:
                candidate = Path(root) / rel
                if candidate.exists():
                    return str(candidate)

    return None


def get_macro_dir():
    """Return the LibreOffice macro directory for the current OS."""
    system = platform.system()
    if system == "Darwin":
        return Path.home() / "Library/Application Support/LibreOffice/4/user/basic/Standard"
    if system == "Windows":
        appdata = os.environ.get("APPDATA")
        if appdata:
            return Path(appdata) / "LibreOffice/4/user/basic/Standard"
        return Path.home() / "AppData/Roaming/LibreOffice/4/user/basic/Standard"
    return Path.home() / ".config/libreoffice/4/user/basic/Standard"


def setup_libreoffice_macro(soffice_binary):
    """Setup LibreOffice macro for recalculation if not already configured."""
    macro_dir = get_macro_dir()
    macro_file = macro_dir / "Module1.xba"

    if macro_file.exists():
        existing = macro_file.read_text(encoding="utf-8", errors="ignore")
        if "RecalculateAndSave" in existing:
            return True

    if not macro_dir.exists():
        try:
            subprocess.run(
                [soffice_binary, "--headless", "--terminate_after_init"],
                capture_output=True,
                check=False,
                timeout=20,
                text=True,
            )
        except Exception:
            pass
        macro_dir.mkdir(parents=True, exist_ok=True)

    macro_content = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
<script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">
    Sub RecalculateAndSave()
      ThisComponent.calculateAll()
      ThisComponent.store()
      ThisComponent.close(True)
    End Sub
</script:module>"""

    try:
        macro_file.write_text(macro_content, encoding="utf-8")
        return True
    except Exception:
        return False


def recalc(filename, timeout=30):
    """
    Recalculate formulas in Excel file and report any errors.

    Args:
        filename: Path to Excel file
        timeout: Maximum time to wait for recalculation (seconds)

    Returns:
        dict with error locations and counts
    """
    file_path = Path(filename).expanduser()
    if not file_path.exists():
        return {"error": f"File {filename} does not exist"}

    soffice_binary = resolve_soffice_binary()
    if not soffice_binary:
        return {
            "error": (
                "LibreOffice executable not found. Install LibreOffice and ensure "
                "`soffice` (or `soffice.com` on Windows) is on PATH."
            )
        }

    if not setup_libreoffice_macro(soffice_binary):
        return {"error": "Failed to setup LibreOffice macro"}

    cmd = [
        soffice_binary,
        "--headless",
        "--norestore",
        "vnd.sun.star.script:Standard.Module1.RecalculateAndSave?language=Basic&location=application",
        str(file_path.resolve()),
    ]

    try:
        run_result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            check=False,
            timeout=timeout,
        )
    except subprocess.TimeoutExpired:
        return {"error": f"Recalculation timed out after {timeout} seconds"}

    if run_result.returncode != 0:
        error_msg = (run_result.stderr or run_result.stdout or "Unknown error during recalculation").strip()
        if "Module1" in error_msg or "RecalculateAndSave" in error_msg or "Basic" in error_msg:
            return {
                "error": "LibreOffice macro not configured properly",
                "details": error_msg,
            }
        return {"error": error_msg}

    try:
        wb_values = load_workbook(file_path, data_only=True)

        excel_errors = ["#VALUE!", "#DIV/0!", "#REF!", "#NAME?", "#NULL!", "#NUM!", "#N/A"]
        error_details = {err: [] for err in excel_errors}
        total_errors = 0

        for sheet_name in wb_values.sheetnames:
            ws = wb_values[sheet_name]
            for row in ws.iter_rows():
                for cell in row:
                    if cell.value is None or not isinstance(cell.value, str):
                        continue
                    for err in excel_errors:
                        if err in cell.value:
                            error_details[err].append(f"{sheet_name}!{cell.coordinate}")
                            total_errors += 1
                            break

        wb_values.close()

        result = {
            "status": "success" if total_errors == 0 else "errors_found",
            "total_errors": total_errors,
            "error_summary": {},
        }

        for err_type, locations in error_details.items():
            if locations:
                result["error_summary"][err_type] = {
                    "count": len(locations),
                    "locations": locations[:20],
                }

        wb_formulas = load_workbook(file_path, data_only=False)
        formula_count = 0
        for sheet_name in wb_formulas.sheetnames:
            ws = wb_formulas[sheet_name]
            for row in ws.iter_rows():
                for cell in row:
                    if isinstance(cell.value, str) and cell.value.startswith("="):
                        formula_count += 1
        wb_formulas.close()

        result["total_formulas"] = formula_count
        return result

    except Exception as exc:
        return {"error": str(exc)}


def main():
    if len(sys.argv) < 2:
        print("Usage: python recalc.py <excel_file> [timeout_seconds]")
        print("\nRecalculates all formulas in an Excel file using LibreOffice")
        print("\nReturns JSON with error details:")
        print("  - status: 'success' or 'errors_found'")
        print("  - total_errors: Total number of Excel errors found")
        print("  - total_formulas: Number of formulas in the file")
        print("  - error_summary: Breakdown by error type with locations")
        print("    - #VALUE!, #DIV/0!, #REF!, #NAME?, #NULL!, #NUM!, #N/A")
        sys.exit(1)

    filename = sys.argv[1]
    timeout = int(sys.argv[2]) if len(sys.argv) > 2 else 30

    result = recalc(filename, timeout)
    print(json.dumps(result, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()
