"""
Common CLI functionality - simplified replacement for removed common module.

This is a minimal replacement to keep existing CLI commands working while
the system transitions to S3-based uploads.
"""

from pathlib import Path
from typing import Any, Dict, List, Optional
import typer
from rich.console import Console
from rich.table import Table


class ValidationError(Exception):
    """Validation error for CLI commands."""
    pass


class BaseCommand:
    """Base class for CLI commands - simplified implementation."""
    
    def __init__(self):
        self.console = Console()
    
    def handle_exception(self, exception: Exception, context: str = "operation") -> None:
        """Handle exceptions with consistent error messaging."""
        self.console.print(f"[red]Error during {context}: {str(exception)}[/red]")
        raise typer.Exit(1)
    
    def get_org_directory(self, org_name: str) -> Path:
        """Get organization directory."""
        return Path(f"cloudzero-demo-billing/orgs/{org_name}")
    
    def get_config_path(self, org_dir: Path, config_file: Optional[str], default_name: str) -> Path:
        """Get configuration file path."""
        if config_file:
            return Path(config_file)
        return org_dir / "billing" / "configs" / default_name
    
    def validate_file_exists(self, file_path: Path, description: str = "file") -> None:
        """Validate that a file exists."""
        if not file_path.exists():
            raise ValidationError(f"{description} not found: {file_path}")


def display_summary_table(console: Console, title: str, data: List[Dict[str, Any]], columns: Optional[List[str]] = None) -> None:
    """Display a summary table - simplified implementation."""
    if not data:
        console.print(f"No data to display for {title}")
        return
    
    # Create table with title if provided
    table = Table(title=title if title else None)
    
    if data:
        # Use provided columns or derive from first row
        if columns:
            # Add specified columns
            for col in columns:
                table.add_column(str(col).replace("_", " ").title())
            
            # Add rows using specified column order
            for row in data:
                table.add_row(*[str(row.get(col, "")) for col in columns])
        else:
            # Add columns based on first row keys
            for key in data[0].keys():
                table.add_column(str(key).replace("_", " ").title())
            
            # Add rows
            for row in data:
                table.add_row(*[str(value) for value in row.values()])
    
    console.print(table)


def extract_date_range_from_files(files: List[Path]) -> tuple:
    """Extract date range from files - simplified implementation."""
    if not files:
        return None, None
    
    # Simple fallback implementation
    return "2024-01-01", "2024-12-31"


def group_files_by_prefix(files: List[Path], prefix: str = "") -> Dict[str, List[Path]]:
    """Group files by prefix - simplified implementation."""
    groups = {}
    for file in files:
        key = file.stem.split("_")[0] if "_" in file.stem else "default"
        if key not in groups:
            groups[key] = []
        groups[key].append(file)
    return groups


def validate_workspace_structure(path: Path) -> bool:
    """Validate workspace structure - simplified implementation."""
    return path.exists() and path.is_dir()


def get_org_dir(org_name: str) -> Path:
    """Get organization directory - simplified implementation."""
    return Path(f"cloudzero-demo-billing/orgs/{org_name}")


def get_latest_run_dir(org_dir: Path) -> Path:
    """Get latest run directory - simplified implementation."""
    runs_dir = org_dir / "billing" / "runs"
    if not runs_dir.exists():
        raise ValidationError(f"No runs directory found: {runs_dir}")
    
    run_dirs = [d for d in runs_dir.iterdir() if d.is_dir()]
    if not run_dirs:
        raise ValidationError(f"No run directories found in {runs_dir}")
    
    return max(run_dirs, key=lambda d: d.stat().st_mtime)


# Export commonly used items
__all__ = [
    "BaseCommand",
    "ValidationError", 
    "display_summary_table",
    "extract_date_range_from_files",
    "group_files_by_prefix",
    "validate_workspace_structure",
    "get_org_dir",
    "get_latest_run_dir"
]