"""
Main CLI entry point for PrecipGen library.

Provides unified command-line interface for all PrecipGen workflows
with consistent error handling and user guidance.
"""

import sys
import argparse
from typing import List, Optional

from precipgen.utils import get_logger, PrecipGenError
from .commands import (
    discover_command,
    analyze_command,
    simulate_command,
    validate_command,
    station_info_command,
    list_outputs_command,
    clean_command
)


def create_parser() -> argparse.ArgumentParser:
    """
    Create the main argument parser with all subcommands.
    
    Returns:
        Configured ArgumentParser instance
    """
    parser = argparse.ArgumentParser(
        prog="precipgen",
        description="PrecipGen: Stochastic precipitation generation library",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  precipgen discover --location "Salt Lake City, UT"
  precipgen discover --lat 40.7 --lon -111.9 --radius 50
  precipgen analyze --data precipitation.csv --station USC00426128
  precipgen simulate --params params.json --days 3650
  precipgen validate --synthetic synthetic.csv --historical historical.csv
  precipgen station-info USC00426128
  precipgen list-outputs
  precipgen clean --station USC00426128

For more help on a specific command, use:
  precipgen <command> --help
        """
    )
    
    parser.add_argument(
        "--version",
        action="version",
        version="%(prog)s 0.1.4"
    )
    
    parser.add_argument(
        "--verbose", "-v",
        action="store_true",
        help="Enable verbose logging"
    )
    
    # Create subparsers for commands
    subparsers = parser.add_subparsers(
        dest="command",
        help="Available commands",
        metavar="COMMAND"
    )
    
    # Add all command parsers
    discover_command.add_parser(subparsers)
    analyze_command.add_parser(subparsers)
    simulate_command.add_parser(subparsers)
    validate_command.add_parser(subparsers)
    station_info_command.add_parser(subparsers)
    list_outputs_command.add_parser(subparsers)
    clean_command.add_parser(subparsers)
    
    return parser


def main(argv: Optional[List[str]] = None) -> int:
    """
    Main CLI entry point.
    
    Args:
        argv: Command line arguments (defaults to sys.argv)
        
    Returns:
        Exit code (0 for success, non-zero for error)
    """
    parser = create_parser()
    
    if argv is None:
        argv = sys.argv[1:]
    
    # Parse arguments
    try:
        args = parser.parse_args(argv)
    except SystemExit as e:
        return e.code if e.code is not None else 1
    
    # Configure logging
    logger = get_logger("precipgen.cli")
    if args.verbose:
        import logging
        logging.getLogger("precipgen").setLevel(logging.DEBUG)
    
    # Handle no command case
    if not hasattr(args, 'command') or args.command is None:
        parser.print_help()
        return 1
    
    # Execute command
    try:
        if args.command == "discover":
            return discover_command.execute(args)
        elif args.command == "analyze":
            return analyze_command.execute(args)
        elif args.command == "simulate":
            return simulate_command.execute(args)
        elif args.command == "validate":
            return validate_command.execute(args)
        elif args.command == "station-info":
            return station_info_command.execute(args)
        elif args.command == "list-outputs":
            return list_outputs_command.execute(args)
        elif args.command == "clean":
            return clean_command.execute(args)
        else:
            logger.error(f"Unknown command: {args.command}")
            return 1
            
    except PrecipGenError as e:
        logger.error(f"PrecipGen error: {e}")
        if args.verbose:
            import traceback
            traceback.print_exc()
        return 1
    except KeyboardInterrupt:
        logger.info("Operation cancelled by user")
        return 130  # Standard exit code for SIGINT
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
        if args.verbose:
            import traceback
            traceback.print_exc()
        return 1


if __name__ == "__main__":
    sys.exit(main())