import subprocess
from pathlib import Path
from geoexpress.config import GEOEXPRESS_BIN
from geoexpress.exceptions import (
    GeoExpressNotInstalled,
    GeoExpressLicenseError,
)


def _get_encoder_path() -> Path:
    exe = GEOEXPRESS_BIN / "mrsidgeoencoder.exe"

    if not exe.exists():
        raise GeoExpressNotInstalled(
            "GeoExpress is not installed or corrupted. "
            "mrsidgeoencoder.exe not found."
        )

    return exe


def ensure_geoexpress_ready():
    """
    Ensure GeoExpress is installed and licensed.
    """

    encoder_exe = r"C:\Program Files\LizardTech\GeoExpress\bin\mrsidgeoencoder.exe"

    try:
        proc = subprocess.run(
            [encoder_exe, "-v"],  # version triggers license check
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            stdin=subprocess.DEVNULL,  # prevents interactive prompt
            timeout=8,
            text=True
        )
    except FileNotFoundError:
        raise GeoExpressNotInstalled(
            "GeoExpress is not installed on this system."
        )
    except subprocess.TimeoutExpired:
        raise GeoExpressLicenseError(
            "GeoExpress license check hung (interactive activation prompt detected)."
        )

    output = (proc.stdout + proc.stderr).lower()

    # --- License Detection Logic ---

    if "could not locate a valid license" in output:
        raise GeoExpressLicenseError(
            "GeoExpress license is not valid. Please activate GeoExpress with a valid serial number."
        )

    if "trial license usage exhausted" in output:
        raise GeoExpressLicenseError(
            "GeoExpress trial license has expired. Please purchase or activate a license."
        )

    if "enter your serial number" in output:
        raise GeoExpressLicenseError(
            "GeoExpress activation required. Please register your product."
        )

    return True
