"""
Main module for command line functionality
"""

import argparse
import json
import logging
from filter import ExcelFilter

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def load_config(config_file: str) -> dict:
    """
    Loads a configuration file
    """
    try:
        with open(config_file, 'r') as f:
            config = json.load(f)
        logger.info(f"Configuration loaded: {config_file}")
        return config
    except Exception as e:
        logger.error(f"Error loading configuration: {e}")
        raise


def main():
    """
    Main function for command line application
    """
    parser = argparse.ArgumentParser(description='Excel Filter Tool')
    parser.add_argument('--input', required=True, help='Input file (Excel)')
    parser.add_argument('--output', required=True, help='Output file (Excel)')
    parser.add_argument('--pattern', help='Regex pattern for filtering')
    parser.add_argument('--config', help='Configuration file (JSON)')
    parser.add_argument('--sheet', help='Name of the worksheet')
    parser.add_argument('--columns', nargs='+', help='Columns to search')

    args = parser.parse_args()

    # Load configuration or use command line arguments
    if args.config:
        config = load_config(args.config)
        pattern = config.get('pattern', args.pattern)
        sheet_name = config.get('sheet_name', args.sheet)
        columns = config.get('columns', args.columns)
    else:
        pattern = args.pattern
        sheet_name = args.sheet
        columns = args.columns

    if not pattern:
        logger.error("No regex pattern specified")
        return

    # Create ExcelFilter instance and execute
    excel_filter = ExcelFilter(
        input_file=args.input,
        output_file=args.output,
        pattern=pattern,
        sheet_name=sheet_name,
        columns=columns
    )

    success = excel_filter.process()
    if success:
        logger.info("Processing completed successfully")
    else:
        logger.error("Processing failed")


if __name__ == '__main__':
    main()
