import os
import requests
from slack_sdk import WebClient
from health.utils.logging_config import setup_logger

logger = setup_logger(__name__)

def download_file(file_path: str, channel_id: str) -> str:
    """
    Uploads a file from the server to Slack.
    
    Args:
        file_path: Absolute path to the file on the server.
        channel_id: Slack channel to upload to.
        
    Returns:
        String message indicating success or failure.
    """
    try:
        if not os.path.exists(file_path):
            return f"❌ File not found: {file_path}"
            
        token = os.environ.get("SHELL_SLACK_BOT_TOKEN") or os.environ.get("SLACK_BOT_TOKEN")
        client = WebClient(token=token)
        
        file_size = os.path.getsize(file_path)
        file_name = os.path.basename(file_path)
        
        # Check size limit (e.g. 50MB)
        if file_size > 50 * 1024 * 1024:
            return f"❌ File too large ({file_size/1024/1024:.1f}MB). Limit is 50MB."
            
        logger.info(f"Uploading {file_path} to {channel_id}")
        
        # files_upload_v2 is the modern way
        client.files_upload_v2(
            channel=channel_id,
            file=file_path,
            title=file_name,
            initial_comment=f"📂 Here is `{file_name}` from the server."
        )
        
        return f"✅ Successfully uploaded `{file_path}` to Slack."
        
    except Exception as e:
        logger.error(f"Download file failed: {e}")
        return f"❌ Error uploading file: {e}"

def save_file(file_path: str, content: str, overwrite: bool = False) -> str:
    """
    Saves text content to a file on the server (Upload to Server).
    
    Args:
        file_path: Target absolute path.
        content: Text content to write.
        overwrite: Whether to overwrite existing files.
        
    Returns:
        Status message.
    """
    try:
        # Security check: Prevent writing to critical system paths? 
        # For now, we trust the authorized user, but maybe block /etc/passwd or similar if needed.
        
        if os.path.exists(file_path) and not overwrite:
            return f"⚠️ File `{file_path}` already exists. Use `overwrite=True` to replace it."
            
        # Ensure directory exists
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(content)
            
        return f"✅ Successfully saved file to `{file_path}` ({len(content)} chars)."
        
    except Exception as e:
        logger.error(f"Save file failed: {e}")
        return f"❌ Error saving file: {e}"
