# -*- coding: utf-8 -*-
import subprocess
import sys
import os
import shutil
import platform
from pathlib import Path

INPUT_DIR = "input"
OUTPUT_DIR = "output"


def find_libreoffice():
    system = platform.system()
    if system == "Darwin":
        candidates = [
            "/Applications/LibreOffice.app/Contents/MacOS/soffice",
        ]
    elif system == "Linux":
        candidates = [
            "/usr/bin/soffice",
            "/usr/lib/libreoffice/program/soffice",
            "/snap/bin/libreoffice.soffice",
        ]
    else:
        candidates = [
            "F:\\libreoffice\\program\\soffice.exe",
            "C:\\Program Files\\LibreOffice\\program\\soffice.exe",
            "C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe",
        ]
    for p in candidates:
        if os.path.isfile(p):
            return p
    found = shutil.which("soffice")
    if found:
        return found
    return None


def convert_single(soffice_path, docx_file, out_dir):
    cmd = [
        soffice_path,
        "--headless",
        "--norestore",
        "--convert-to", "doc",
        "--outdir", str(out_dir),
        str(docx_file),
    ]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    return result.returncode == 0


def convert_docx_to_doc(input_dir, output_dir):
    input_path = Path(input_dir)
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    soffice = find_libreoffice()
    if not soffice:
        print("[ERROR] LibreOffice not found!")
        print("[ERROR] https://www.libreoffice.org/download/download/")
        return

    print("[INFO] LibreOffice: " + soffice)

    docx_files = [
        f for f in input_path.rglob("*.docx")
        if not f.name.startswith("~$")
    ]

    total = len(docx_files)
    if total == 0:
        print("[WARN] No .docx files found in: " + str(input_path.resolve()))
        return

    print("[INFO] Found " + str(total) + " .docx files\n")

    success = 0
    fail = 0

    for idx, docx_file in enumerate(docx_files, 1):
        rel = docx_file.relative_to(input_path)
        target_dir = output_path / rel.parent
        target_dir.mkdir(parents=True, exist_ok=True)

        try:
            ok = convert_single(soffice, docx_file, target_dir)
            if ok:
                expected_doc = target_dir / (docx_file.stem + ".doc")
                if expected_doc.exists():
                    success += 1
                    print("  [" + str(idx) + "/" + str(total) + "] OK   " + str(rel))
                else:
                    fail += 1
                    print("  [" + str(idx) + "/" + str(total) + "] FAIL " + str(rel) + " -> no output")
            else:
                fail += 1
                print("  [" + str(idx) + "/" + str(total) + "] FAIL " + str(rel) + " -> convert error")
        except subprocess.TimeoutExpired:
            fail += 1
            print("  [" + str(idx) + "/" + str(total) + "] FAIL " + str(rel) + " -> timeout")
        except Exception as e:
            fail += 1
            print("  [" + str(idx) + "/" + str(total) + "] FAIL " + str(rel) + " -> " + str(e))

    print("\n[DONE] OK: " + str(success) + "  FAIL: " + str(fail))
    print("[DONE] Output: " + str(output_path.resolve()))


if __name__ == "__main__":
    convert_docx_to_doc(INPUT_DIR, OUTPUT_DIR)
