"""Media command - Upload and manage WordPress media"""

import click
from praisonaiwp.core.config import Config
from praisonaiwp.core.ssh_manager import SSHManager
from praisonaiwp.core.wp_client import WPClient
from praisonaiwp.utils.logger import get_logger
from rich.console import Console

console = Console()
logger = get_logger(__name__)


@click.command()
@click.argument('file_path')
@click.option('--post-id', type=int, help='Post ID to attach media to')
@click.option('--title', help='Media title')
@click.option('--caption', help='Media caption')
@click.option('--alt', help='Alt text for images')
@click.option('--desc', help='Media description')
@click.option('--server', default=None, help='Server name from config')
def media_command(file_path, post_id, title, caption, alt, desc, server):
    """
    Upload media to WordPress
    
    Examples:
    
        # Upload a file
        praisonaiwp media /path/to/image.jpg
        
        # Upload and attach to post
        praisonaiwp media /path/to/image.jpg --post-id 123
        
        # Upload with metadata
        praisonaiwp media /path/to/image.jpg --title "My Image" --alt "Description"
        
        # Upload from URL
        praisonaiwp media https://example.com/image.jpg
    """
    
    try:
        # Load configuration
        config = Config()
        server_config = config.get_server(server)
        
        console.print(f"\n[yellow]Uploading media...[/yellow]")
        
        with SSHManager(
            server_config['hostname'],
            server_config['username'],
            server_config.get('key_filename'),
            server_config.get('port', 22)
        ) as ssh:
            
            wp = WPClient(
                ssh,
                server_config['wp_path'],
                server_config.get('php_bin', 'php'),
                server_config.get('wp_cli', '/usr/local/bin/wp')
            )
            
            # Build kwargs for import_media
            kwargs = {}
            if title:
                kwargs['title'] = title
            if caption:
                kwargs['caption'] = caption
            if alt:
                kwargs['alt'] = alt
            if desc:
                kwargs['desc'] = desc
            
            attachment_id = wp.import_media(file_path, post_id=post_id, **kwargs)
            
            console.print(f"[green]✓ Uploaded media with ID: {attachment_id}[/green]")
            console.print(f"File: {file_path}")
            if post_id:
                console.print(f"Attached to post: {post_id}")
            console.print()
    
    except Exception as e:
        console.print(f"[red]Error: {e}[/red]")
        logger.error(f"Media command failed: {e}")
        raise click.Abort()
