"""Smart path resolution for common locations."""

import os
import platform
from typing import Optional, Dict, List
from pathlib import Path


class PathResolver:
    """Resolves user-friendly path shortcuts to actual system paths."""
    
    def __init__(self):
        self._system = platform.system()
        self._cache = {}
        self._init_common_paths()
    
    def _init_common_paths(self):
        """Initialize common path mappings."""
        if self._system == "Windows":
            user_profile = os.environ.get("USERPROFILE", "")
            self._cache = {
                "desktop": os.path.join(user_profile, "Desktop"),
                "documents": os.path.join(user_profile, "Documents"),
                "downloads": os.path.join(user_profile, "Downloads"),
                "pictures": os.path.join(user_profile, "Pictures"),
                "videos": os.path.join(user_profile, "Videos"),
                "music": os.path.join(user_profile, "Music"),
                "home": user_profile,
                "temp": os.environ.get("TEMP", ""),
                "appdata": os.environ.get("APPDATA", ""),
                "programfiles": os.environ.get("PROGRAMFILES", ""),
            }
        else:  # Linux/Mac
            home = os.path.expanduser("~")
            self._cache = {
                "desktop": os.path.join(home, "Desktop"),
                "documents": os.path.join(home, "Documents"),
                "downloads": os.path.join(home, "Downloads"),
                "pictures": os.path.join(home, "Pictures"),
                "videos": os.path.join(home, "Videos"),
                "music": os.path.join(home, "Music"),
                "home": home,
                "temp": "/tmp",
            }
    
    def resolve(self, path_input: str) -> str:
        """Resolve a path input to actual system path.
        
        Args:
            path_input: User input like "desktop", "my desktop", "C:\\full\\path"
            
        Returns:
            Resolved absolute path
        """
        # Already absolute path
        if os.path.isabs(path_input):
            return path_input
        
        # Normalize input
        normalized = path_input.lower().strip()
        
        # Remove common prefixes
        for prefix in ["my ", "the ", "on ", "in ", "at "]:
            if normalized.startswith(prefix):
                normalized = normalized[len(prefix):]
        
        # Direct match
        if normalized in self._cache:
            return self._cache[normalized]
        
        # Fuzzy match
        for key, value in self._cache.items():
            if key in normalized or normalized in key:
                return value
        
        # Relative to current directory
        return os.path.abspath(path_input)
    
    def get_system_context(self) -> Dict[str, any]:
        """Get system context for LLM."""
        import psutil
        
        # Get drives
        drives = []
        if self._system == "Windows":
            for partition in psutil.disk_partitions():
                drives.append({
                    "drive": partition.device,
                    "mountpoint": partition.mountpoint,
                    "fstype": partition.fstype
                })
        
        # Get current user
        current_user = os.environ.get("USERNAME") or os.environ.get("USER", "unknown")
        
        return {
            "os": self._system,
            "user": current_user,
            "common_paths": self._cache,
            "drives": drives,
            "cwd": os.getcwd()
        }
