import sys
from pathlib import Path
import subprocess
import logging
import shutil

from pypdf import PdfWriter

logger = logging.getLogger(__name__)


def _is_mac() -> bool:
    return sys.platform == "darwin"


def _get_libreoffice_path():
    if _is_mac():
        return "/Applications/LibreOffice.app/Contents/MacOS/soffice"
    return "libreoffice"


def has_libreoffice() -> bool:
    if _is_mac():
        return Path(_get_libreoffice_path()).exists()
    return shutil.which("libreoffice") is not None


def doc_to_pdf(path: Path) -> bool:

    tool = _get_libreoffice_path()
    cmd = f"{tool} --headless --convert-to pdf {path} --outdir {path.parent}"
    try:
        subprocess.run(cmd, shell=True, check=True, capture_output=True)
    except subprocess.CalledProcessError as e:
        logger.warn("Error converting pdf:", e.stderr)
        return False
    return True


def merge_pdfs(output: Path, paths: list[Path]):

    merger = PdfWriter()
    for path in paths:
        merger.append(path)
    merger.write(output)
