"""Configuration management for pytest-cream workspaces."""
import json
import os
from pathlib import Path
from typing import Optional, Dict, Any


CONFIG_FILE = ".pytest-cream.json"


def get_config_path() -> Path:
    """Get the path to the config file in the current working directory."""
    return Path.cwd() / CONFIG_FILE


def load_config() -> Dict[str, Any]:
    """Load the configuration file."""
    config_path = get_config_path()
    if not config_path.exists():
        return {}
    
    try:
        with open(config_path, 'r') as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        return {}


def save_config(config: Dict[str, Any]) -> None:
    """Save the configuration file."""
    config_path = get_config_path()
    try:
        with open(config_path, 'w') as f:
            json.dump(config, f, indent=2)
    except IOError as e:
        print(f"Warning: Could not save config file: {e}")


def set_last_workspace(workspace: str, repo: Optional[str] = None, branch: Optional[str] = None) -> None:
    """
    Store the last used workspace information.
    
    Args:
        workspace: The workspace directory path
        repo: Optional repository name (owner/repo)
        branch: Optional branch name
    """
    config = load_config()
    
    workspace_info = {
        "path": os.path.abspath(workspace),
    }
    
    if repo:
        workspace_info["repo"] = repo
    if branch:
        workspace_info["branch"] = branch
    
    config["last_workspace"] = workspace_info
    save_config(config)


def get_last_workspace() -> Optional[Dict[str, str]]:
    """
    Retrieve the last used workspace information.
    
    Returns:
        Dictionary with workspace info or None if not found
    """
    config = load_config()
    return config.get("last_workspace")


def resolve_workspace(workspace: Optional[str] = None) -> Optional[str]:
    """
    Resolve the workspace path. If not provided, use the last workspace.
    Also handles finding the correct subdirectory (repo_clone).
    
    Args:
        workspace: Optional workspace path
        
    Returns:
        Resolved workspace path or None
    """
    if workspace:
        ws_path = os.path.abspath(workspace)
    else:
        last_ws = get_last_workspace()
        if not last_ws:
            return None
        ws_path = last_ws["path"]
    
    # Check if the workspace exists
    if not os.path.exists(ws_path):
        return None
    
    # If workspace contains timestamped subdirectories, find the most recent one
    if os.path.isdir(ws_path):
        # Look for pytest_cream_* directories
        subdirs = [d for d in os.listdir(ws_path) if d.startswith("pytest_cream_") and os.path.isdir(os.path.join(ws_path, d))]
        
        if subdirs:
            # Sort by timestamp (newest first)
            subdirs.sort(reverse=True)
            most_recent = subdirs[0]
            
            # Check if there's a repo_clone subdirectory
            repo_clone_path = os.path.join(ws_path, most_recent, "repo_clone")
            if os.path.exists(repo_clone_path):
                return repo_clone_path
            
            # Otherwise return the timestamped directory
            return os.path.join(ws_path, most_recent)
    
    return ws_path


def resolve_python_executable(workspace: str, python_executable: Optional[str] = None) -> Optional[str]:
    """
    Resolve the Python executable path. If not provided, look for .venv in workspace.
    
    Args:
        workspace: The workspace directory
        python_executable: Optional Python executable path
        
    Returns:
        Resolved Python executable path or None
    """
    if python_executable:
        return python_executable
    
    # First resolve the workspace to get the actual path (including repo_clone if exists)
    resolved_ws = resolve_workspace(workspace)
    if not resolved_ws:
        resolved_ws = workspace
    
    # Look for .venv in the resolved workspace
    venv_python = os.path.join(resolved_ws, ".venv", "bin", "python")
    if os.path.exists(venv_python):
        return venv_python
    
    # Also check the parent directory (in case workspace is already repo_clone)
    parent_venv = os.path.join(os.path.dirname(resolved_ws), ".venv", "bin", "python")
    if os.path.exists(parent_venv):
        return parent_venv
    
    return None


def clear_config() -> None:
    """Clear the configuration file."""
    config_path = get_config_path()
    if config_path.exists():
        config_path.unlink()
