import json
import os
from functools import lru_cache
from typing import Dict

# Default manifest path inside app images; override with env
DEFAULT_MANIFEST_PATH = os.environ.get(
    'EVEAI_STATIC_MANIFEST_PATH',
    '/app/config/static-manifest/manifest.json'
)


@lru_cache(maxsize=1)
def _load_manifest(manifest_path: str = DEFAULT_MANIFEST_PATH) -> Dict[str, str]:
    try:
        with open(manifest_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception:
        return {}


def resolve_asset(logical_path: str, manifest_path: str = DEFAULT_MANIFEST_PATH) -> str:
    """
    Map a logical asset path (e.g. 'dist/chat-client.js') to the hashed path
    found in the Parcel manifest. If not found or manifest missing, return the
    original logical path for graceful fallback.
    """
    if not logical_path:
        return logical_path

    manifest = _load_manifest(manifest_path)

    # Try several key variants as Parcel manifests may use different keys
    candidates = [
        logical_path,
        logical_path.lstrip('/'),
        logical_path.replace('static/', ''),
        logical_path.replace('dist/', ''),
    ]

    for key in candidates:
        if key in manifest:
            return manifest[key]

    return logical_path
