from __future__ import annotations

import shutil
import subprocess
from pathlib import Path

from .models import DependencyStatus
from .paths import project_root

COMMON_WINDOWS_TESSERACT_PATHS = (
    Path("C:/Program Files/Tesseract-OCR/tesseract.exe"),
    Path("C:/Program Files (x86)/Tesseract-OCR/tesseract.exe"),
)


def parse_tesseract_languages(output: str) -> set[str]:
    return {
        line.strip()
        for line in output.splitlines()
        if line.strip() and not line.startswith("List of available")
    }


def find_tesseract() -> str | None:
    tesseract = shutil.which("tesseract")
    if tesseract:
        return tesseract
    for path in COMMON_WINDOWS_TESSERACT_PATHS:
        if path.exists():
            return str(path)
    return None


def workspace_tessdata_prefix() -> str | None:
    tessdata = project_root() / "tools" / "tessdata"
    if (tessdata / "vie.traineddata").exists():
        return str(tessdata)
    return None


def check_tesseract() -> DependencyStatus:
    tesseract = find_tesseract()
    if not tesseract:
        return DependencyStatus(False, None, False, None, ["missing_tesseract"])
    tessdata_prefix = workspace_tessdata_prefix()

    try:
        env = None
        if tessdata_prefix:
            import os

            env = os.environ.copy()
            env["TESSDATA_PREFIX"] = tessdata_prefix
        proc = subprocess.run(
            [tesseract, "--list-langs"],
            check=False,
            capture_output=True,
            text=True,
            timeout=10,
            env=env,
        )
    except Exception as exc:
        return DependencyStatus(True, tesseract, False, tessdata_prefix, [f"tesseract_language_check_failed:{exc}"])

    warnings: list[str] = []
    languages = parse_tesseract_languages(proc.stdout + "\n" + proc.stderr)
    if "vie" not in languages:
        warnings.append("missing_tesseract_vie_language")
    return DependencyStatus(True, tesseract, "vie" in languages, tessdata_prefix, warnings)
