#!/usr/bin/env python3
"""
Command Line Interface for NLPAP
"""

import argparse
import sys
from .nlp_analyzer import ComprehensiveNLP


def main():
    """Main CLI function"""
    parser = argparse.ArgumentParser(
        description="NLPAP - NLP Analyzer Package - Command Line Interface",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  nlpap-analyze --text "I feel stressed about my studies"
  nlpap-analyze --file input.txt
  nlpap-analyze --demo
        """
    )
    
    parser.add_argument(
        '--text', '-t',
        type=str,
        help='Single text to analyze'
    )
    
    parser.add_argument(
        '--file', '-f',
        type=str,
        help='File containing texts to analyze (one per line)'
    )
    
    parser.add_argument(
        '--demo', '-d',
        action='store_true',
        help='Run demo with sample texts'
    )
    
    parser.add_argument(
        '--task',
        choices=['all', 'preprocess', 'semantic', 'sentiment'],
        default='all',
        help='Which task to run (default: all)'
    )
    
    parser.add_argument(
        '--version', '-v',
        action='version',
        version='NLPAP 1.0.0'
    )
    
    args = parser.parse_args()
    
    # Initialize analyzer
    try:
        nlp = ComprehensiveNLP()
    except Exception as e:
        print(f"Error initializing NLP analyzer: {e}")
        sys.exit(1)
    
    # Get texts to analyze
    texts = []
    
    if args.text:
        texts = [args.text]
    elif args.file:
        try:
            with open(args.file, 'r', encoding='utf-8') as f:
                texts = [line.strip() for line in f if line.strip()]
        except FileNotFoundError:
            print(f"Error: File '{args.file}' not found")
            sys.exit(1)
        except Exception as e:
            print(f"Error reading file: {e}")
            sys.exit(1)
    elif args.demo:
        texts = nlp.sample_texts
        print("Running demo with sample mental health texts...")
    else:
        parser.print_help()
        sys.exit(1)
    
    if not texts:
        print("Error: No texts to analyze")
        sys.exit(1)
    
    # Run analysis based on task
    try:
        if args.task == 'all':
            results = nlp.run_complete_analysis(texts)
        elif args.task == 'preprocess':
            processed_data, tokens = nlp.preprocess_text(texts)
            results = {'processed_data': processed_data, 'tokens': tokens}
        elif args.task == 'semantic':
            _, tokens = nlp.preprocess_text(texts)
            semantic_data = nlp.semantic_analysis(tokens)
            results = {'semantic_data': semantic_data}
        elif args.task == 'sentiment':
            entities, sentiments = nlp.information_extraction_and_sentiment(texts)
            results = {'entities': entities, 'sentiments': sentiments}
        
        print(f"\n{'='*50}")
        print("CLI Analysis Complete!")
        print(f"{'='*50}")
        
    except Exception as e:
        print(f"Error during analysis: {e}")
        sys.exit(1)


if __name__ == '__main__':
    main()