"""
Command Line Interface for CORE

Usage:
    core-register --source SOURCE_WSI --target TARGET_WSI [options]
"""

import argparse
import sys


def main():
    """Main entry point for the CORE CLI."""
    parser = argparse.ArgumentParser(
        prog='core-register',
        description='CORE - Cell-Level Coarse-to-Fine Image Registration Engine',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='''
Examples:
  # Basic registration
  core-register --source moving.svs --target fixed.svs --output result.mha

  # With custom resolution
  core-register --source moving.svs --target fixed.svs --resolution 0.625

  # Full pipeline with nuclei-level refinement
  core-register --source moving.svs --target fixed.svs --fine-registration
'''
    )
    
    # Required arguments
    parser.add_argument(
        '--source', '-s',
        type=str,
        required=True,
        help='Path to the source (moving) WSI file'
    )
    
    parser.add_argument(
        '--target', '-t',
        type=str,
        required=True,
        help='Path to the target (fixed) WSI file'
    )
    
    # Optional arguments
    parser.add_argument(
        '--output', '-o',
        type=str,
        default='deformation_field.mha',
        help='Path to save the output deformation field (default: deformation_field.mha)'
    )
    
    parser.add_argument(
        '--resolution',
        type=float,
        default=0.625,
        help='Resolution for coarse registration (default: 0.625)'
    )
    
    parser.add_argument(
        '--fine-registration',
        action='store_true',
        help='Enable nuclei-level fine registration'
    )
    
    parser.add_argument(
        '--fine-resolution',
        type=float,
        default=40.0,
        help='Resolution for fine registration (default: 40.0)'
    )
    
    parser.add_argument(
        '--patch-size',
        type=int,
        nargs=2,
        default=[1000, 1000],
        help='Patch size for nuclei extraction (default: 1000 1000)'
    )
    
    parser.add_argument(
        '--verbose', '-v',
        action='store_true',
        help='Enable verbose output'
    )
    
    parser.add_argument(
        '--version',
        action='version',
        version='%(prog)s 1.0.0'
    )
    
    args = parser.parse_args()
    
    # Import here to avoid slow startup
    try:
        from core.preprocessing.preprocessing import load_wsi_images, extract_tissue_masks
        from core.registration.rigid import rigid_registration
        from core.utils.util import create_displacement_field_for_wsi
        import SimpleITK as sitk
        import numpy as np
    except ImportError as e:
        print(f"Error: Missing required module - {e}", file=sys.stderr)
        print("Please ensure all dependencies are installed.", file=sys.stderr)
        sys.exit(1)
    
    try:
        # Load images
        if args.verbose:
            print(f"Loading WSI images...")
            print(f"  Source: {args.source}")
            print(f"  Target: {args.target}")
        
        source_wsi, target_wsi, source, target = load_wsi_images(
            args.source, 
            args.target, 
            resolution=args.resolution
        )
        
        # Extract tissue masks
        if args.verbose:
            print("Extracting tissue masks...")
        
        source_mask, target_mask = extract_tissue_masks(source, target, artefacts=False)
        
        # Perform rigid registration
        if args.verbose:
            print("Performing rigid registration...")
        
        aligned_image, transform_matrix, metrics = rigid_registration(
            source, target, source_mask, target_mask, verbose=args.verbose
        )
        
        if args.verbose:
            print(f"Registration metrics: {metrics}")
        
        # Create displacement field
        if args.verbose:
            print("Creating displacement field...")
        
        displacement_field = create_displacement_field_for_wsi(
            transform_matrix, source, target
        )
        
        # Save output
        if args.verbose:
            print(f"Saving deformation field to {args.output}...")
        
        sitk_image = sitk.GetImageFromArray(displacement_field)
        sitk.WriteImage(sitk_image, args.output)
        
        print(f"Registration complete! Output saved to: {args.output}")
        
        if args.fine_registration:
            print("\nNote: Fine registration with nuclei-level refinement is not yet")
            print("implemented in the CLI. Please use the Python API or notebooks.")
        
        return 0
        
    except FileNotFoundError as e:
        print(f"Error: File not found - {e}", file=sys.stderr)
        return 1
    except Exception as e:
        print(f"Error during registration: {e}", file=sys.stderr)
        if args.verbose:
            import traceback
            traceback.print_exc()
        return 1


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