"""Staging configuration files into instance directories."""

import logging
from pathlib import Path

logger = logging.getLogger(__name__)


def ensure_instance_directory(instance_id: str, base_path: str | None = None) -> str:
    """Create and return the instance directory path.

    Args:
        instance_id: Unique instance identifier
        base_path: Base directory for all instances (defaults to Settings.instance_base_path)

    Returns:
        Absolute path to instance directory
    """
    if base_path is None:
        from src.config import Settings

        base_path = Settings().instance_base_path
    instance_dir = Path(base_path) / instance_id
    instance_dir.mkdir(parents=True, exist_ok=True)
    return str(instance_dir.absolute())


def write_env_file(instance_dir: str, env_vars: dict[str, str]) -> str:
    """Write environment variables to a .env file.

    Args:
        instance_dir: Path to instance directory
        env_vars: Dictionary of env var names to values

    Returns:
        Path to the env file
    """
    env_path = Path(instance_dir) / ".env"
    lines = [f'{key}="{value}"' for key, value in env_vars.items()]
    env_path.write_text("\n".join(lines) + "\n")
    return str(env_path)


def write_config_files(instance_dir: str, files: dict[str, str]) -> None:
    """Write config files to the instance directory.

    Args:
        instance_dir: Path to instance directory
        files: Dictionary of file paths (relative to instance dir) to content
    """
    instance_path = Path(instance_dir)
    for file_path, content in files.items():
        # Ensure the path is within the instance directory (security)
        full_path = instance_path / file_path
        try:
            full_path.resolve().relative_to(instance_path.resolve())
        except ValueError:
            raise ValueError(f"File path '{file_path}' escapes instance directory")

        full_path.parent.mkdir(parents=True, exist_ok=True)
        full_path.write_text(content)
