"""Utilities for locating bundled data files."""
from pathlib import Path
import sys

try:
    # Python 3.9+
    from importlib.resources import files
    HAS_IMPORTLIB_RESOURCES = True
except ImportError:
    HAS_IMPORTLIB_RESOURCES = False


def get_data_dir() -> Path:
    """Get the directory containing bundled data files.
    
    Priority:
    1. Installed package data (using importlib.resources)
    2. Source directory (development)
    3. Current working directory (fallback)
    """
    
    # Try using importlib.resources first (best for installed packages)
    if HAS_IMPORTLIB_RESOURCES:
        try:
            blocking_files = files('fsm_crawl').joinpath('blocking')
            # Try to resolve the path
            if hasattr(blocking_files, 'iterdir'):
                # It's a Traversable, try to get a real path
                return Path(str(blocking_files))
        except Exception:
            pass
    
    # Check if running from source (development)
    current_dir = Path(__file__).parent.parent.parent
    blocking_dir = current_dir / "blocking"
    
    if blocking_dir.exists():
        return blocking_dir
    
    # Check installed package location
    try:
        import fsm_crawl
        package_dir = Path(fsm_crawl.__file__).parent
        blocking_dir = package_dir / "blocking"
        
        if blocking_dir.exists():
            return blocking_dir
    except Exception:
        pass
    
    # Check parent of package
    try:
        import fsm_crawl
        package_parent = Path(fsm_crawl.__file__).parent.parent
        blocking_dir = package_parent / "blocking"
        
        if blocking_dir.exists():
            return blocking_dir
    except Exception:
        pass
    
    # Fallback to current working directory
    cwd_blocking = Path.cwd() / "blocking"
    if cwd_blocking.exists():
        return cwd_blocking
    
    # Last resort - return current working directory blocking
    return Path.cwd() / "blocking"


def get_consent_manager_path() -> str:
    """Get path to consent manager YAML file."""
    data_dir = get_data_dir()
    yaml_path = data_dir / "consent-manager.yaml"
    
    if yaml_path.exists():
        return str(yaml_path)
    
    # Fallback
    return "blocking/consent-manager.yaml"


def get_url_file_path(filename: str) -> str:
    """Get path to a URL data file."""
    data_dir = get_data_dir()
    file_path = data_dir / filename
    
    if file_path.exists():
        return str(file_path)
    
    # Fallback to current working directory
    return str(Path.cwd() / "blocking" / filename)
