import os
from typing import Optional


def _try_frontend_path(base_path: str, relative_path: str) -> Optional[str]:
    frontend_path = os.path.join(base_path, "frontend", relative_path)
    if os.path.exists(frontend_path):
        return frontend_path
    return None


def get_resource_path(relative_path: str) -> str:
    """
    Get the absolute path to a resource, compatible with PyPI package structure.
    """
    base_path = os.path.dirname(os.path.abspath(__file__))

    # If using PyInstaller, sys._MEIPASS might be relevant, but for PyPI wheel:
    # resources should be included in MANIFEST.in or package_data.

    # Let's check 'frontend' subdirectory first, then root of package
    frontend_path = _try_frontend_path(base_path, relative_path)
    if frontend_path:
        return frontend_path

    return os.path.join(base_path, relative_path)


def get_frontend_url() -> str:
    """
    Returns the file:/// URL for the local index.html.
    """
    path = get_resource_path("index.html")
    if not os.path.exists(path):
        # Fallback or strict error?
        # The previous webview implementation handled the check.
        # Here we just return the path.
        pass

    return f"file:///{path.replace(os.sep, '/')}"
