"""Application and module version registry for Warehouse/FlyWMS bridge."""

from __future__ import annotations

from pathlib import Path


APP_VERSION = "1.0.0"

MODULE_VERSIONS: dict[str, str] = {
    "app": APP_VERSION,
    "async_loop_singleton": "1.0.0",
    "async_msssql_query": "1.0.1",
    "audit_log": "1.0.0",
    "main": "1.0.1",
    "barcode_client": "1.0.25",
    "barcode_repository": "1.0.12",
    "barcode_service": "1.0.24",
    "busy_overlay": "1.0.0",
    "db_config": "1.0.0",
    "gestione_aree": "1.0.1",
    "gestione_layout": "1.0.2",
    "gestione_pickinglist": "1.0.4",
    "gestione_scarico": "1.0.8",
    "locale_text": "1.0.0",
    "login_window": "1.0.0",
    "prenota_sprenota_sql": "1.0.1",
    "reset_corsie": "1.0.0",
    "runtime_support": "1.0.1",
    "search_pallets": "1.0.0",
    "storico_pickinglist": "1.0.3",
    "storico_udc": "1.0.0",
    "tooltips": "1.0.0",
    "udc_non_scaffalate": "1.0.1",
    "ui_theme": "1.0.0",
    "user_session": "1.0.0",
    "view_celle_multi_udc": "1.0.0",
    "window_placement": "1.0.0",
}


def module_key(module_name: str) -> str:
    """Return the stable registry key for a module name or path."""

    name = str(module_name or "").replace("\\", "/")
    stem = Path(name).stem if "/" in name or "." not in name else name.rsplit(".", 1)[-1]
    return stem or "app"


def module_version(module_name: str | None = None) -> str:
    """Return the version for a module, falling back to the app version."""

    if not module_name:
        return APP_VERSION
    return MODULE_VERSIONS.get(module_key(module_name), APP_VERSION)


def version_label(module_name: str | None = None) -> str:
    """Return the standard visual label used in window titles."""

    return f"ver. {module_version(module_name)}"


def versioned_title(title: str, module_name: str | None = None) -> str:
    """Append the standard version label to a window title."""

    clean_title = str(title or "").strip()
    label = version_label(module_name)
    if not clean_title:
        return label
    if label.lower() in clean_title.lower():
        return clean_title
    return f"{clean_title} - {label}"
