"""
Station info command implementation.

Implements the 'precipgen station-info' command for displaying
station metadata and directory information.
"""

import argparse
import json
from pathlib import Path
from typing import Optional

from precipgen.utils import get_logger
from precipgen.utils.directory_manager import DirectoryManager


def add_parser(subparsers) -> argparse.ArgumentParser:
    """
    Add station-info command parser to subparsers.
    
    Args:
        subparsers: ArgumentParser subparsers object
        
    Returns:
        The station-info command parser
    """
    parser = subparsers.add_parser(
        "station-info",
        help="Display station metadata and directory information",
        description="Show detailed information about a station's data and analysis outputs",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  precipgen station-info USC00426128
  precipgen station-info USC00426128 --output-dir /path/to/analysis
  precipgen station-info USC00426128 --save-metadata
        """
    )
    
    # Required station ID
    parser.add_argument(
        "station_id",
        type=str,
        help="GHCN station identifier (e.g., USC00426128)"
    )
    
    # Output options
    parser.add_argument(
        "--output-dir", "-o",
        type=str,
        help="Custom output directory (default: ./precipgen_output)"
    )
    
    parser.add_argument(
        "--save-metadata",
        action="store_true",
        help="Save station metadata to JSON file"
    )
    
    parser.add_argument(
        "--format",
        choices=["table", "json", "detailed"],
        default="detailed",
        help="Output format (default: detailed)"
    )
    
    return parser


def format_file_size(size_bytes: float) -> str:
    """
    Format file size in human-readable format.
    
    Args:
        size_bytes: Size in bytes
        
    Returns:
        Formatted size string
    """
    if size_bytes < 1024:
        return f"{size_bytes:.1f} B"
    elif size_bytes < 1024 * 1024:
        return f"{size_bytes / 1024:.1f} KB"
    else:
        return f"{size_bytes / (1024 * 1024):.1f} MB"


def display_station_info_table(station_info) -> None:
    """
    Display station information in table format.
    
    Args:
        station_info: StationDirectory object
    """
    print(f"Station: {station_info.station_id}")
    print("-" * 40)
    print(f"Directory: {station_info.directory_path}")
    print(f"Total Size: {format_file_size(station_info.total_size_mb * 1024 * 1024)}")
    print(f"Last Modified: {station_info.last_modified.strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    print("File Counts by Workflow:")
    print(f"  Data:       {len(station_info.data_files)}")
    print(f"  Analysis:   {len(station_info.analysis_files)}")
    print(f"  Simulation: {len(station_info.simulation_files)}")
    print(f"  Validation: {len(station_info.validation_files)}")


def display_station_info_detailed(station_info) -> None:
    """
    Display detailed station information.
    
    Args:
        station_info: StationDirectory object
    """
    print(f"Station Information: {station_info.station_id}")
    print("=" * 60)
    print()
    
    # Directory information
    print("Directory Structure:")
    print(f"  Base Path: {station_info.directory_path}")
    print(f"  Total Size: {format_file_size(station_info.total_size_mb * 1024 * 1024)}")
    print(f"  Last Modified: {station_info.last_modified.strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    # Data files
    if station_info.data_files:
        print("Data Files:")
        for file_path in station_info.data_files:
            print(f"  • {file_path}")
        print()
    
    # Analysis files
    if station_info.analysis_files:
        print("Analysis Files:")
        for file_path in station_info.analysis_files:
            print(f"  • {file_path}")
        print()
    
    # Simulation files
    if station_info.simulation_files:
        print("Simulation Files:")
        for file_path in station_info.simulation_files:
            print(f"  • {file_path}")
        print()
    
    # Validation files
    if station_info.validation_files:
        print("Validation Files:")
        for file_path in station_info.validation_files:
            print(f"  • {file_path}")
        print()
    
    # Summary
    total_files = (len(station_info.data_files) + len(station_info.analysis_files) + 
                  len(station_info.simulation_files) + len(station_info.validation_files))
    
    print("Summary:")
    print(f"  Total Files: {total_files}")
    print(f"  Workflows Completed:")
    
    if station_info.data_files:
        print("    ✓ Data Acquisition")
    else:
        print("    ✗ Data Acquisition")
    
    if station_info.analysis_files:
        print("    ✓ Data Analysis")
    else:
        print("    ✗ Data Analysis")
    
    if station_info.simulation_files:
        print("    ✓ Simulation")
    else:
        print("    ✗ Simulation")
    
    if station_info.validation_files:
        print("    ✓ Validation")
    else:
        print("    ✗ Validation")


def display_station_info_json(station_info) -> None:
    """
    Display station information in JSON format.
    
    Args:
        station_info: StationDirectory object
    """
    station_data = {
        "station_id": station_info.station_id,
        "directory_path": str(station_info.directory_path),
        "total_size_mb": station_info.total_size_mb,
        "last_modified": station_info.last_modified.isoformat(),
        "file_counts": {
            "data": len(station_info.data_files),
            "analysis": len(station_info.analysis_files),
            "simulation": len(station_info.simulation_files),
            "validation": len(station_info.validation_files)
        },
        "files": {
            "data": station_info.data_files,
            "analysis": station_info.analysis_files,
            "simulation": station_info.simulation_files,
            "validation": station_info.validation_files
        },
        "workflows_completed": {
            "data_acquisition": len(station_info.data_files) > 0,
            "data_analysis": len(station_info.analysis_files) > 0,
            "simulation": len(station_info.simulation_files) > 0,
            "validation": len(station_info.validation_files) > 0
        }
    }
    
    print(json.dumps(station_data, indent=2))


def save_station_metadata(station_info, dir_manager: DirectoryManager) -> str:
    """
    Save station metadata to JSON file.
    
    Args:
        station_info: StationDirectory object
        dir_manager: Directory manager instance
        
    Returns:
        Path to saved metadata file
    """
    # Save to data directory
    data_dir = dir_manager.get_subdirectory(station_info.station_id, "data")
    metadata_path = data_dir / "station_info.json"
    
    metadata = {
        "station_id": station_info.station_id,
        "directory_path": str(station_info.directory_path),
        "total_size_mb": station_info.total_size_mb,
        "last_modified": station_info.last_modified.isoformat(),
        "file_counts": {
            "data": len(station_info.data_files),
            "analysis": len(station_info.analysis_files),
            "simulation": len(station_info.simulation_files),
            "validation": len(station_info.validation_files)
        },
        "files": {
            "data": station_info.data_files,
            "analysis": station_info.analysis_files,
            "simulation": station_info.simulation_files,
            "validation": station_info.validation_files
        },
        "workflows_completed": {
            "data_acquisition": len(station_info.data_files) > 0,
            "data_analysis": len(station_info.analysis_files) > 0,
            "simulation": len(station_info.simulation_files) > 0,
            "validation": len(station_info.validation_files) > 0
        },
        "generated_at": station_info.last_modified.isoformat()
    }
    
    with open(metadata_path, 'w') as f:
        json.dump(metadata, f, indent=2)
    
    return str(metadata_path)


def execute(args) -> int:
    """
    Execute the station-info command.
    
    Args:
        args: Parsed command line arguments
        
    Returns:
        Exit code (0 for success, non-zero for error)
    """
    logger = get_logger("precipgen.cli.station_info")
    
    try:
        # Initialize directory manager
        dir_manager = DirectoryManager(args.output_dir or "./precipgen_output")
        
        # Get station information
        station_info = dir_manager.get_station_info(args.station_id, args.output_dir)
        
        if not station_info:
            print(f"Error: Station directory not found for {args.station_id}")
            print("\nTroubleshooting:")
            print("  • Check that the station ID is correct")
            print("  • Verify that workflows have been run for this station")
            print("  • List available stations:")
            print("    precipgen list-outputs")
            print("  • Run discovery to find stations:")
            print("    precipgen discover --location \"Your Location\"")
            return 1
        
        # Display information based on format
        if args.format == "table":
            display_station_info_table(station_info)
        elif args.format == "json":
            display_station_info_json(station_info)
        else:  # detailed
            display_station_info_detailed(station_info)
        
        # Save metadata if requested
        if args.save_metadata:
            metadata_path = save_station_metadata(station_info, dir_manager)
            print(f"\nMetadata saved to: {metadata_path}")
        
        return 0
        
    except Exception as e:
        logger.error(f"Unexpected error in station-info command: {e}")
        print(f"Error: {e}")
        return 1