"""Asset path resolution for bundled ONNX weights and JSON metadata.

Uses :mod:`importlib.resources` to locate files inside the installed
package, falling back to a user-supplied directory if provided.
"""
from __future__ import annotations

from importlib.resources import as_file, files
from pathlib import Path

from ai_mouse.errors import ModelLoadError

_PACKAGE_ASSETS = "ai_mouse.assets"


def bundled_path(name: str) -> Path:
    """Return a filesystem path to a bundled asset.

    Args:
        name: filename inside the assets/ directory.

    Returns:
        A concrete :class:`pathlib.Path`. For non-zip wheels (the common
        case) the path points directly into the installed package; for
        zipapp installations :func:`importlib.resources.as_file`
        materialises a temp file.
    """
    ref = files(_PACKAGE_ASSETS) / name
    with as_file(ref) as p:
        return Path(p)


def resolve(model_path: Path | None, filename: str) -> Path:
    """Locate an asset given an optional user-supplied directory.

    Args:
        model_path: user-supplied directory, or None to use bundled assets.
        filename: file to locate inside the directory.

    Returns:
        Absolute path to the asset.

    Raises:
        ModelLoadError: if the file does not exist.
    """
    if model_path is None:
        p = bundled_path(filename)
    else:
        p = Path(model_path) / filename
    if not p.exists():
        raise ModelLoadError(f"Required asset missing: {p}")
    return p
